Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ae53e83ff3 | ||
|
|
ef84e18f46
|
||
|
|
cf1be16763
|
||
|
|
cc8428643a
|
||
|
|
70251ff3ce | ||
|
|
76dc34a17c
|
||
|
|
a6a0c7c11e
|
||
|
|
f759387eb7
|
||
|
|
21b3591da1
|
||
|
|
e9937ded6b
|
||
|
|
bd1acdd0cc
|
||
|
|
a2c6341544
|
||
|
|
cb3372ac76
|
||
|
|
48e605a545
|
||
|
|
9a4e59f0e0
|
||
|
|
820beda72f
|
||
|
|
c6f70de82d
|
||
|
|
f37f6e2453
|
||
|
|
f7a999e317
|
||
|
|
45494d5b43
|
||
|
|
9ca9545847
|
||
|
|
fa14e7da80
|
||
|
|
12eea5eee3
|
||
|
|
ef623f6c68
|
||
|
|
ee2d19d011
|
||
|
|
53c6b3e413
|
||
|
|
d58125c0bc
|
||
|
|
029198ff61
|
||
|
|
0b08fc5242
|
||
|
|
93609c7ab3
|
||
|
|
461d3dc1f7
|
||
|
|
94f79177a2
|
||
|
|
9169e9db09
|
||
|
|
0d0cd09124
|
||
|
|
0dc5bf9a9b
|
||
|
|
ca107f6977
|
||
|
|
4dad1415e6
|
||
|
|
5bf0a696c6
|
||
|
|
7a8d948fcb
|
||
|
|
d90f7d48d0
|
||
|
|
c5a43f21aa
|
||
|
|
d3fbb0842f
|
||
|
|
dafd426316
|
||
|
|
bec374aa92
|
||
|
|
85b21578d8
|
||
|
|
03c25e7214
|
||
|
|
c30624a59e
|
||
|
|
3cf025fb4a
|
||
|
|
81b784876b
|
||
|
|
6c42f64bfa | ||
|
|
d74216c6b7
|
||
|
|
0b7ce448ab
|
||
|
|
2fb8c09a00
|
||
|
|
0442f1849f
|
||
|
|
cf049797b0
|
||
|
|
18e6fe6af6
|
||
|
|
e8a84d3e41
|
||
|
|
c5f4541cbf
|
||
|
|
369e5038ca
|
||
|
|
66862a1bab
|
||
|
|
25dcdb2d19
|
||
|
|
1830a89898
|
||
|
|
6e718e165a
|
||
|
|
0a37b551f5
|
||
|
|
864b87faa6
|
||
|
|
d55d8580cf
|
||
|
|
63229d1711
|
No files matched your search
@@ -20,12 +20,11 @@ jobs:
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Verify extension namespace support
|
||||
run: |
|
||||
if [ -e /proc/sys/kernel/apparmor_restrict_unprivileged_userns ]; then
|
||||
sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0
|
||||
fi
|
||||
unshare --user --map-root-user --net true
|
||||
# ripgrep and the unprivileged-userns sysctl are provisioned on the host.
|
||||
# A self-hosted runner should not need sudo, and installing a package on
|
||||
# every run is not the gate's job.
|
||||
- name: Verify unprivileged user namespaces
|
||||
run: unshare --user --map-root-user --net true
|
||||
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
@@ -46,9 +45,6 @@ jobs:
|
||||
go install mvdan.cc/gofumpt@v0.11.0
|
||||
bash tools/proto.sh install
|
||||
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y --no-install-recommends ripgrep
|
||||
|
||||
- name: Ensure contract baseline ref
|
||||
run: |
|
||||
if ! git show-ref --verify --quiet refs/heads/main; then
|
||||
|
||||
@@ -21,6 +21,17 @@ jobs:
|
||||
cut:
|
||||
runs-on: self-hosted
|
||||
steps:
|
||||
# A mirror carries its own Actions secrets. An empty token checks out
|
||||
# fine and fails at the push instead, which reads as a broken release.
|
||||
- name: Check DEPLOY_TOKEN is configured
|
||||
env:
|
||||
DEPLOY_TOKEN: ${{ secrets.DEPLOY_TOKEN }}
|
||||
run: |
|
||||
if [ -z "$DEPLOY_TOKEN" ]; then
|
||||
echo "::error::DEPLOY_TOKEN is not set for this repository, so the release cannot push its commit and tag. Set the secret here, or dispatch the release from the Gitea primary."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# DEPLOY_TOKEN rather than the job token: a push made with the job token
|
||||
# doesn't start workflows, and the tag push must start deploy.yml.
|
||||
- name: Checkout
|
||||
|
||||
@@ -47,3 +47,4 @@ __pycache__/
|
||||
|
||||
# Local symlink to the archipelago marketplace repo
|
||||
/archipelago
|
||||
.agents-run/
|
||||
@@ -5,6 +5,42 @@ release's per-component sections are labelled beneath its heading.
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [1.61.1] - 2026-11-07
|
||||
|
||||
### archie-gateway
|
||||
|
||||
- An image or voice attachment that arrives as a link is now checked against what the link serves, the same as an uploaded one. A link whose content is not the declared type, or that cannot be read, is refused.
|
||||
|
||||
### archie-ui
|
||||
|
||||
- A workflow created on the canvas now saves the agent it runs as, so it runs instead of parking with "declares no identity to run as".
|
||||
|
||||
### archie-state-store
|
||||
|
||||
- A workflow that no longer validates after an upgrade (for example it names a step type that was removed) is repaired at startup instead of breaking every workflow. A shipped workflow is restored from this release's copy; a workflow you created is removed and logged, and its earlier revision stays in the resource history. Valid workflows you created or edited are kept.
|
||||
|
||||
## [1.61.0] - 2026-11-07
|
||||
|
||||
### archied
|
||||
|
||||
- A `workflow.handoff` now finishes its run and starts a separate, linked run of the next workflow on the same issue, instead of continuing as another attempt. The task page links each run to the one before and after it; attempts count only retries of one run.
|
||||
|
||||
- A task no longer fails to prepare its worktree with "some refs were not updated" after a tag or branch moves on the forge.
|
||||
|
||||
### archie-ui
|
||||
|
||||
- The task page no longer flashes its loading state on every live update while a task runs.
|
||||
|
||||
### archie-state-store
|
||||
|
||||
- The extension catalogue lists and installs again. Its default signing key has changed; an instance that set its own catalogue signing key in Extension settings keeps using that key.
|
||||
|
||||
## [1.60.0] - 2026-11-02
|
||||
|
||||
### archied
|
||||
|
||||
- Curators can list a repository's open issues and file new ones with the `issue_list` and `issue_create` tools, which reach the forge through the daemon. A curator files only when its definition declares `issue_create`; the shipped self-intake example runs in dry run with `issue_list` for deduplication. Listing every open issue needs the forge extensions from the archipelago release after 1.2.0.
|
||||
|
||||
## [1.59.0] - 2026-11-02
|
||||
|
||||
### archied
|
||||
|
||||
@@ -47,6 +47,21 @@ then pushes `main` and the tag atomically with `DEPLOY_TOKEN`. A push made with
|
||||
the job token wouldn't start other workflows, so the user token is what lets
|
||||
the tag start the deploy.
|
||||
|
||||
Every workflow that reaches the registry or the canary reads its credentials
|
||||
from Actions secrets, so a mirror of this repository carries its own set:
|
||||
|
||||
| Name | Kind | Used by |
|
||||
|---|---|---|
|
||||
| `DEPLOY_TOKEN` | secret | release, deploy, canary, promote — the registry push, the tag push, and the package links |
|
||||
| `RELEASE_SIGNING_KEY` | secret | deploy — signs the release statement |
|
||||
| `CANARY_TOKEN` | secret | deploy, canary, promote — the canary's dashboard API |
|
||||
| `CANARY_URL` | variable | deploy, canary, promote — where that dashboard is |
|
||||
| `CANARY_WINDOW` | variable | canary — the judged window; empty means the default |
|
||||
|
||||
A mirror missing them fails at its first login or push; `release.yml` names the
|
||||
missing `DEPLOY_TOKEN` before it checks out, so the run doesn't read as a broken
|
||||
release.
|
||||
|
||||
After a release, pull `main` before committing on it again: CI has added the
|
||||
release commit.
|
||||
|
||||
|
||||
@@ -156,6 +156,15 @@ _needs a repository._
|
||||
| `push` | bool | Push the branch after committing. |
|
||||
| `reference` | `Fixes` \| `Implements` \| `Refs` | How the commit links to the task issue. |
|
||||
|
||||
Hooks never run. The commit is created by go-git, which ignores `.git/hooks`
|
||||
and `core.hooksPath`, and the agent never runs git, so `pre-commit`,
|
||||
`commit-msg` and `prepare-commit-msg` in the checkout are inert files. A
|
||||
repository whose rules live only in a hook — a formatter, a secret scanner,
|
||||
commitlint, a DCO trailer — gets a commit that does not satisfy them: the run
|
||||
reports success and the pull request fails the check afterwards. Put the same
|
||||
commands in `command.run` or the repository gate, which both run in the task
|
||||
container before this step.
|
||||
|
||||
### `repo.open-pr`
|
||||
|
||||
_needs a repository._
|
||||
|
||||
+6
-4
@@ -101,11 +101,13 @@ target = "127.0.0.1:9090"
|
||||
# [[curators]]
|
||||
# name = "self-intake"
|
||||
# interval = "1h"
|
||||
# tools = ["run_list", "run_events"]
|
||||
# tools = ["run_list", "run_events", "issue_list"]
|
||||
# instructions = """
|
||||
# You are archie's self-intake curator, in dry run. Each pass: list recent
|
||||
# task runs with run_list, inspect anything parked or failed with run_events,
|
||||
# then report candidate follow-up issues — concrete, each tied to the run
|
||||
# that produced it. Do not create issues; this pass reports only (no
|
||||
# issue-creating tool is declared, so it cannot).
|
||||
# check issue_list for each repo so nothing already open is repeated, then
|
||||
# report candidate follow-up issues, each tied to the run that produced it.
|
||||
# Do not create issues.
|
||||
# """
|
||||
# To let it file: add "issue_create" to tools and tell it to file each
|
||||
# candidate (citing the run) instead of only reporting it.
|
||||
@@ -52,7 +52,7 @@ listen = "127.0.0.1:8587"
|
||||
[[curators]]
|
||||
name = "self-intake"
|
||||
interval = "1h"
|
||||
tools = ["run_list", "run_events"]
|
||||
tools = ["run_list", "run_events", "issue_list"]
|
||||
instructions = """
|
||||
You are archie's self-intake curator, in dry run. Each pass: list recent task runs with run_list, inspect anything parked or failed with run_events, then report candidate follow-up issues — concrete, each tied to the run that produced it. Do not create issues; this pass reports only (no issue-creating tool is declared, so it cannot). End your reply with the report.
|
||||
You are archie's self-intake curator, in dry run. Each pass: list recent task runs with run_list, inspect anything parked or failed with run_events, check issue_list for each repo so nothing already open is repeated, then report candidate follow-up issues — concrete, each tied to the run that produced it. Do not create issues; this pass reports only (no issue-creating tool is declared, so it cannot). End your reply with the report.
|
||||
"""
|
||||
@@ -90,6 +90,9 @@
|
||||
"/news/archie/1.58.1/": "/news/1.58.1/",
|
||||
"/news/archie/1.59.0/": "/news/1.59.0/",
|
||||
"/news/archie/1.6.0/": "/news/1.6.0/",
|
||||
"/news/archie/1.60.0/": "/news/1.60.0/",
|
||||
"/news/archie/1.61.0/": "/news/1.61.0/",
|
||||
"/news/archie/1.61.1/": "/news/1.61.1/",
|
||||
"/news/archie/1.7.0/": "/news/1.7.0/",
|
||||
"/news/archie/1.8.0/": "/news/1.8.0/",
|
||||
"/news/archie/1.9.0/": "/news/1.9.0/",
|
||||
@@ -195,6 +198,9 @@
|
||||
"/news/archied/1.58.1/": "/news/1.58.1/",
|
||||
"/news/archied/1.59.0/": "/news/1.59.0/",
|
||||
"/news/archied/1.6.0/": "/news/1.6.0/",
|
||||
"/news/archied/1.60.0/": "/news/1.60.0/",
|
||||
"/news/archied/1.61.0/": "/news/1.61.0/",
|
||||
"/news/archied/1.61.1/": "/news/1.61.1/",
|
||||
"/news/archied/1.7.0/": "/news/1.7.0/",
|
||||
"/news/archied/1.8.0/": "/news/1.8.0/",
|
||||
"/news/archied/1.9.0/": "/news/1.9.0/",
|
||||
|
||||
@@ -1,4 +1,19 @@
|
||||
[
|
||||
{
|
||||
"version": "1.61.1",
|
||||
"date": "2026-11-07",
|
||||
"body": "### archie-gateway\n\n- An image or voice attachment that arrives as a link is now checked against what the link serves, the same as an uploaded one. A link whose content is not the declared type, or that cannot be read, is refused.\n\n### archie-ui\n\n- A workflow created on the canvas now saves the agent it runs as, so it runs instead of parking with \"declares no identity to run as\".\n\n### archie-state-store\n\n- A workflow that no longer validates after an upgrade (for example it names a step type that was removed) is repaired at startup instead of breaking every workflow. A shipped workflow is restored from this release's copy; a workflow you created is removed and logged, and its earlier revision stays in the resource history. Valid workflows you created or edited are kept."
|
||||
},
|
||||
{
|
||||
"version": "1.61.0",
|
||||
"date": "2026-11-07",
|
||||
"body": "### archied\n\n- A `workflow.handoff` now finishes its run and starts a separate, linked run of the next workflow on the same issue, instead of continuing as another attempt. The task page links each run to the one before and after it; attempts count only retries of one run.\n\n- A task no longer fails to prepare its worktree with \"some refs were not updated\" after a tag or branch moves on the forge.\n\n### archie-ui\n\n- The task page no longer flashes its loading state on every live update while a task runs.\n\n### archie-state-store\n\n- The extension catalogue lists and installs again. Its default signing key has changed; an instance that set its own catalogue signing key in Extension settings keeps using that key."
|
||||
},
|
||||
{
|
||||
"version": "1.60.0",
|
||||
"date": "2026-11-02",
|
||||
"body": "### archied\n\n- Curators can list a repository's open issues and file new ones with the `issue_list` and `issue_create` tools, which reach the forge through the daemon. A curator files only when its definition declares `issue_create`; the shipped self-intake example runs in dry run with `issue_list` for deduplication. Listing every open issue needs the forge extensions from the archipelago release after 1.2.0."
|
||||
},
|
||||
{
|
||||
"version": "1.59.0",
|
||||
"date": "2026-11-02",
|
||||
|
||||
@@ -1,9 +1,14 @@
|
||||
// Keyboard and phone access: the task dialog fits and tabs in order, pages
|
||||
// title correctly, the skip link and palette focus main content, and
|
||||
// query-only tab switches keep focus where it is.
|
||||
// query-only tab switches keep focus where it is. Then the audit's two
|
||||
// static sweeps (#1767): no unnamed controls on any route, and every keyboard
|
||||
// focus stop's indicator clears 3:1 against the background behind it.
|
||||
const assert = require('node:assert/strict');
|
||||
const { staticRoutes } = require('./helpers/routes.cjs');
|
||||
|
||||
module.exports = async ({ page, go, shot, settled }) => {
|
||||
module.exports = async ({ page, go, shot, fail, settled, tolerate }) => {
|
||||
// The extension catalogue 502 is a stack-environment issue, not this check.
|
||||
tolerate(/extensions\/catalogue/);
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
await go('/tasks');
|
||||
await page.getByRole('button', { name: 'Jump to', exact: true }).click();
|
||||
@@ -35,7 +40,7 @@ module.exports = async ({ page, go, shot, settled }) => {
|
||||
assert.ok(await skip.evaluate(el => el === document.activeElement), 'Skip link is not the first keyboard stop');
|
||||
await page.keyboard.press('Enter');
|
||||
assert.equal(await page.evaluate(() => document.activeElement?.id), 'main-content');
|
||||
await page.getByRole('button', { name: 'Sections', exact: true }).click();
|
||||
await page.getByRole('button', { name: 'Toggle Sidebar', exact: true }).click();
|
||||
await page.getByRole('navigation', { name: 'Sections', exact: true }).getByRole('link', { name: 'Tasks', exact: true }).click();
|
||||
await page.waitForFunction(() => document.activeElement?.id === 'main-content', null, { timeout: 5000 }).catch(() => {});
|
||||
assert.equal(await page.evaluate(() => document.activeElement?.id), 'main-content', 'route navigation did not focus main');
|
||||
@@ -50,4 +55,122 @@ module.exports = async ({ page, go, shot, settled }) => {
|
||||
const tab = page.getByRole('tab', { name: /^Map/ });
|
||||
await tab.click();
|
||||
assert.ok(await tab.evaluate(el => el === document.activeElement), 'query-only navigation stole focus');
|
||||
|
||||
await page.setViewportSize({ width: 1440, height: 900 });
|
||||
|
||||
// Unnamed controls: every visible input, textarea, select, button or
|
||||
// widget role on each static route needs an accessible name (accname
|
||||
// order: labelledby, label, content, value, placeholder, title).
|
||||
for (const r of staticRoutes()) {
|
||||
await go(r);
|
||||
const unnamed = await page.evaluate(() => {
|
||||
const name = (el) => {
|
||||
const by = el.getAttribute('aria-labelledby');
|
||||
if (by) {
|
||||
const t = by.split(/\s+/).map((id) => (document.getElementById(id)?.textContent || '')).join(' ').trim();
|
||||
if (t) return t;
|
||||
}
|
||||
const al = el.getAttribute('aria-label');
|
||||
if (al && al.trim()) return al.trim();
|
||||
if (el.id) {
|
||||
const l = document.querySelector(`label[for="${CSS.escape(el.id)}"]`);
|
||||
if (l && l.textContent.trim()) return l.textContent.trim();
|
||||
}
|
||||
const wrap = el.closest('label');
|
||||
if (wrap && wrap.textContent.trim()) return wrap.textContent.trim();
|
||||
if (el.tagName === 'BUTTON' || el.getAttribute('role') === 'button' || el.getAttribute('role') === 'tab' || el.getAttribute('role') === 'switch') return el.textContent.trim();
|
||||
if (el.tagName === 'INPUT') {
|
||||
const t = (el.getAttribute('type') || 'text').toLowerCase();
|
||||
if (t === 'submit' || t === 'button' || t === 'reset') return el.value.trim();
|
||||
if (t === 'image') return (el.getAttribute('alt') || '').trim();
|
||||
}
|
||||
return (el.getAttribute('placeholder') || el.getAttribute('title') || '').trim();
|
||||
};
|
||||
return [...document.querySelectorAll('button, input, textarea, select, [role="button"], [role="tab"], [role="switch"], [role="checkbox"]')]
|
||||
.filter((el) => el.type !== 'hidden' && el.getClientRects().length)
|
||||
.filter((el) => !name(el))
|
||||
.map((el) => `${el.tagName.toLowerCase()}${el.id ? '#' + el.id : ''}: ${el.outerHTML.slice(0, 120)}`);
|
||||
});
|
||||
for (const u of unnamed) fail(`unnamed control on ${r}: ${u}`);
|
||||
}
|
||||
|
||||
// Focus contrast: Tab through each static route; the focused element's
|
||||
// outline or ring must clear 3:1 against the effective background behind it.
|
||||
const focusProbe = () => page.evaluate(() => {
|
||||
const el = document.activeElement;
|
||||
if (!el || el === document.body || el === document.documentElement) return null;
|
||||
const cs = getComputedStyle(el);
|
||||
const parse = (c) => {
|
||||
c = String(c).trim();
|
||||
let m = c.match(/rgba?\(([^)]+)\)/);
|
||||
if (m) {
|
||||
const p = m[1].split(',').map(Number);
|
||||
return { r: p[0], g: p[1], b: p[2], a: p.length > 3 ? p[3] : 1 };
|
||||
}
|
||||
m = c.match(/^#([0-9a-f]{3,8})$/i);
|
||||
if (m) {
|
||||
let h = m[1];
|
||||
if (h.length === 3 || h.length === 4) h = [...h].map((x) => x + x).join('');
|
||||
const n = parseInt(h.slice(0, 6), 16);
|
||||
return { r: (n >> 16) & 255, g: (n >> 8) & 255, b: n & 255, a: h.length === 8 ? parseInt(h.slice(6, 8), 16) / 255 : 1 };
|
||||
}
|
||||
return null;
|
||||
};
|
||||
const bgBehind = (start) => {
|
||||
for (let n = start; n; n = n.parentElement) {
|
||||
const c = parse(getComputedStyle(n).backgroundColor);
|
||||
if (c && c.a > 0) return c;
|
||||
}
|
||||
return { r: 255, g: 255, b: 255, a: 1 };
|
||||
};
|
||||
// An outer ring or outline is painted over the parent's background; an
|
||||
// inset one over the element's own. Score against whichever is higher.
|
||||
const bgSelf = bgBehind(el);
|
||||
const bgParent = bgBehind(el.parentElement);
|
||||
const over = (fg, bg) => {
|
||||
const a = fg.a + bg.a * (1 - fg.a);
|
||||
if (a === 0) return { r: 0, g: 0, b: 0 };
|
||||
return { r: (fg.r * fg.a + bg.r * bg.a * (1 - fg.a)) / a, g: (fg.g * fg.a + bg.g * bg.a * (1 - fg.a)) / a, b: (fg.b * fg.a + bg.b * bg.a * (1 - fg.a)) / a };
|
||||
};
|
||||
const lum = (c) => {
|
||||
const f = (v) => { v /= 255; return v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4); };
|
||||
return 0.2126 * f(c.r) + 0.7152 * f(c.g) + 0.0722 * f(c.b);
|
||||
};
|
||||
const ratio = (c1, c2) => {
|
||||
const l1 = lum(c1), l2 = lum(c2);
|
||||
return (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
|
||||
};
|
||||
let fg = null;
|
||||
// The ring lives in --tw-ring-shadow on :focus-visible; read the var
|
||||
// directly, then fall back to outline, any shadow layer, focus border.
|
||||
if (el.matches(':focus-visible')) {
|
||||
const m = cs.getPropertyValue('--tw-ring-shadow').match(/rgba?\([^)]+\)|#[0-9a-f]{3,8}\b/i);
|
||||
if (m) { const c = parse(m[0]); if (c && c.a > 0) fg = c; }
|
||||
}
|
||||
if (!fg && cs.outlineStyle !== 'none' && parseFloat(cs.outlineWidth) > 0) fg = parse(cs.outlineColor === 'currentcolor' ? cs.color : cs.outlineColor);
|
||||
if (!fg && cs.boxShadow && cs.boxShadow !== 'none') {
|
||||
for (const m of cs.boxShadow.matchAll(/rgba?\([^)]+\)|#[0-9a-f]{3,8}\b/gi)) {
|
||||
const c = parse(m[0]);
|
||||
if (c && c.a > 0) { fg = c; break; }
|
||||
}
|
||||
}
|
||||
if (!fg && el.matches(':focus-visible') && parseFloat(cs.borderTopWidth) > 0) {
|
||||
const c = parse(cs.borderTopColor);
|
||||
if (c && c.a > 0) fg = c;
|
||||
}
|
||||
const sig = `${el.tagName}#${el.id}:${(el.textContent || '').trim().slice(0, 30)}`;
|
||||
if (!fg) return { sig, ratio: 0 };
|
||||
return { sig, ratio: Math.max(ratio(over(fg, bgSelf), bgSelf), ratio(over(fg, bgParent), bgParent)) };
|
||||
});
|
||||
for (const r of staticRoutes()) {
|
||||
await go(r);
|
||||
let prev = '';
|
||||
for (let i = 0; i < 40; i++) {
|
||||
await page.keyboard.press('Tab');
|
||||
const info = await focusProbe();
|
||||
if (!info || info.sig === prev) break;
|
||||
prev = info.sig;
|
||||
if (info.ratio < 3) fail(`focus indicator under 3:1 on ${r} at ${info.sig} (ratio ${info.ratio.toFixed(2)})`);
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,19 @@
|
||||
// The dashboard's static routes, read from the router source so a new page is
|
||||
// swept automatically. Parameterised and redirect routes are skipped.
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
function staticRoutes() {
|
||||
const src = fs.readFileSync(path.join(__dirname, '../../../ui/src/router/index.ts'), 'utf8');
|
||||
const out = [];
|
||||
for (const line of src.split('\n')) {
|
||||
if (/redirect:/.test(line)) continue;
|
||||
const m = line.match(/path: "([^"]*)"/);
|
||||
if (!m || m[1].includes(':')) continue;
|
||||
if (m[1].startsWith('/')) out.push(m[1]);
|
||||
else if (m[1]) out.push('/org/' + m[1]);
|
||||
}
|
||||
return [...new Set(out)];
|
||||
}
|
||||
|
||||
module.exports = { staticRoutes };
|
||||
@@ -1,5 +1,7 @@
|
||||
const assert=require('node:assert/strict');
|
||||
module.exports=async({page,go,shot})=>{
|
||||
module.exports=async({page,go,shot,tolerate})=>{
|
||||
// The extension catalogue 502 is a stack-environment issue, not this check.
|
||||
tolerate(/extensions\/catalogue/);
|
||||
await page.route('**/api/access/policies',async route=>{await new Promise(r=>setTimeout(r,2200));await route.continue()});
|
||||
await go('/access/policies');
|
||||
assert.equal(await page.getByText('No policies yet.',{exact:true}).count(),0);
|
||||
@@ -16,4 +18,19 @@ module.exports=async({page,go,shot})=>{
|
||||
await page.getByRole('button',{name:'Retry runs',exact:true}).click();
|
||||
await page.getByRole('alert').filter({hasText:'Could not load recent runs'}).waitFor({state:'hidden'});
|
||||
await shot('recovered');
|
||||
// A failed list read is an error, never the empty state (#1767): force each
|
||||
// page's list API to 500 and check its empty-state copy stays hidden.
|
||||
const failList = async (pattern,path,emptyTexts,errorSel='[role=alert]')=>{
|
||||
await page.route(pattern,route=>route.fulfill({status:200,contentType:'application/json',body:'unreadable response'}));
|
||||
await go(path);
|
||||
await page.locator(errorSel).first().waitFor();
|
||||
for(const text of emptyTexts) assert.equal(await page.getByText(text,{exact:true}).count(),0,`${path} shows its empty state ("${text}") while the list read fails`);
|
||||
await page.unroute(pattern);
|
||||
};
|
||||
await failList('**/api/tasks*','/tasks',['No tasks yet'],'text=Archie is not responding');
|
||||
await failList('**/api/captures*','/events',['No captures yet']);
|
||||
await failList('**/api/event-types*','/events',['No event types yet']);
|
||||
await failList('**/api/tokens*','/account',['No tokens yet']);
|
||||
await failList('**/api/access/policies*','/org/policies',['No policies yet']);
|
||||
await shot('failed-reads-show-errors');
|
||||
};
|
||||
@@ -1,4 +1,4 @@
|
||||
// The topbar org selector: choosing a member org reloads the dashboard into it,
|
||||
// The sidebar org switcher: choosing a member org reloads the dashboard into it,
|
||||
// Tasks and Workflows then show only that org's work, and the API refuses an
|
||||
// org the caller is not a member of.
|
||||
const assert = require('node:assert/strict');
|
||||
@@ -8,11 +8,12 @@ module.exports = async ({ page, go, shot, settled, tolerate }) => {
|
||||
tolerate(ABSENT);
|
||||
await go('/tasks');
|
||||
await page.getByText('Fix flaky login test').first().waitFor();
|
||||
const picker = page.getByRole('combobox', { name: 'Organisation' });
|
||||
const picker = page.getByRole('button', { name: /^Organisation: / });
|
||||
await picker.waitFor();
|
||||
const offered = await (async () => {
|
||||
await picker.click();
|
||||
const names = await page.getByRole('option').allInnerTexts();
|
||||
await page.getByRole('menuitem').first().waitFor();
|
||||
const names = (await page.getByRole('menuitem').allInnerTexts()).map(t => t.trim().split('\n').pop().trim());
|
||||
await page.keyboard.press('Escape');
|
||||
return names;
|
||||
})();
|
||||
@@ -22,9 +23,9 @@ module.exports = async ({ page, go, shot, settled, tolerate }) => {
|
||||
await shot('home-org-workflows');
|
||||
|
||||
await picker.click();
|
||||
await Promise.all([page.waitForEvent('load'), page.getByRole('option', { name: 'Beta', exact: true }).click()]);
|
||||
await Promise.all([page.waitForEvent('load'), page.getByRole('menuitem', { name: 'Beta' }).click()]);
|
||||
await settled('/workflows');
|
||||
await page.getByRole('combobox', { name: 'Organisation' }).waitFor();
|
||||
await page.getByRole('button', { name: /^Organisation: / }).waitFor();
|
||||
assert.equal(await page.getByText('Parked', { exact: true }).count(), 0, 'workflow run counts leaked across orgs');
|
||||
await shot('beta-workflows');
|
||||
await go('/tasks');
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
// Phone-width sweep of the views the November audit flagged (#1757): at
|
||||
// 390x844 each must fit without horizontal scroll or clipped controls. The
|
||||
// topbar (with its instance badge) is on every page; /account holds the
|
||||
// token form, /org/agents the agent rows and the grants card, /events the
|
||||
// sources table, the event-type rule editor and the mapping editor dialog.
|
||||
const assert = require('node:assert/strict');
|
||||
const { staticRoutes } = require('./helpers/routes.cjs');
|
||||
|
||||
module.exports = async ({ page, go, shot, fail, settled, tolerate }) => {
|
||||
// The extension catalogue 502 is a stack-environment issue, not this check.
|
||||
tolerate(/extensions\/catalogue/);
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
|
||||
const assertNoOverflow = async (label) => {
|
||||
const { scrollWidth, innerWidth } = await page.evaluate(() => ({
|
||||
scrollWidth: document.documentElement.scrollWidth,
|
||||
innerWidth: window.innerWidth,
|
||||
}));
|
||||
if (scrollWidth > innerWidth) {
|
||||
fail(`${label} overflows 390px: scrollWidth=${scrollWidth} > innerWidth=${innerWidth}`);
|
||||
}
|
||||
};
|
||||
|
||||
const visit = async (path, label, waitFor) => {
|
||||
await go(path);
|
||||
if (waitFor) await settled(waitFor);
|
||||
await assertNoOverflow(label);
|
||||
await shot(label);
|
||||
};
|
||||
|
||||
await visit('/account', 'account-tokens', 'text=API tokens');
|
||||
await visit('/org/agents', 'org-agents', 'text=Credential grants');
|
||||
|
||||
await go('/events');
|
||||
await settled('[role=tab]');
|
||||
await assertNoOverflow('events');
|
||||
await shot('events');
|
||||
|
||||
// The seeded event type's rule editor (RuleEditor's condition row) opens
|
||||
// from the Edit button on its row.
|
||||
const editType = page.locator('button[aria-label^="Edit "]').first();
|
||||
if (await editType.count()) {
|
||||
await editType.click();
|
||||
await page.getByRole('dialog').first().waitFor();
|
||||
await settled();
|
||||
await assertNoOverflow('event-type rule editor');
|
||||
await shot('rule-editor');
|
||||
await page.keyboard.press('Escape');
|
||||
await settled();
|
||||
}
|
||||
|
||||
// The mappings tab's editor dialog carries the payload tree.
|
||||
await page.getByRole('tab', { name: 'Map' }).click();
|
||||
await settled('text=New mapping');
|
||||
await assertNoOverflow('mappings list');
|
||||
const editMapping = page.locator('button', { hasText: 'Edit' }).first();
|
||||
if (await editMapping.count()) {
|
||||
await editMapping.click();
|
||||
await page.getByRole('dialog').first().waitFor();
|
||||
await settled();
|
||||
await assertNoOverflow('mapping editor dialog');
|
||||
await shot('mapping-editor');
|
||||
}
|
||||
|
||||
// Every static route fits 390px (#1767): horizontal scroll fails.
|
||||
for (const r of staticRoutes()) {
|
||||
await visit(r, `route ${r}`, null);
|
||||
}
|
||||
};
|
||||
+2
-16
@@ -1,24 +1,10 @@
|
||||
// Every static route loads without errors, renders, and shows no text with
|
||||
// stray leading, trailing or doubled spaces.
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
function routes() {
|
||||
const src = fs.readFileSync(path.join(__dirname, '../../ui/src/router/index.ts'), 'utf8');
|
||||
const out = [];
|
||||
for (const line of src.split('\n')) {
|
||||
if (/redirect:/.test(line)) continue;
|
||||
const m = line.match(/path: "([^"]*)"/);
|
||||
if (!m || m[1].includes(':')) continue;
|
||||
if (m[1].startsWith('/')) out.push(m[1]);
|
||||
else if (m[1]) out.push('/org/' + m[1]);
|
||||
}
|
||||
return [...new Set(out)];
|
||||
}
|
||||
const { staticRoutes } = require('./helpers/routes.cjs');
|
||||
|
||||
module.exports = async ({ page, go, shot, fail }) => {
|
||||
const stray = new Map();
|
||||
for (const r of routes()) {
|
||||
for (const r of staticRoutes()) {
|
||||
await go(r);
|
||||
await shot(r);
|
||||
// Log lines are data, not copy.
|
||||
|
||||
@@ -50,6 +50,7 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/controlplanestore"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/eventbus/nats"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/extension"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/issuerpc"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/kitrun"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/logrpc"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/messagingrpc"
|
||||
@@ -587,9 +588,30 @@ func (b *boot) registerNATSRPC() error {
|
||||
return err
|
||||
}
|
||||
b.addCleanup(unsubscribeTaskActions)
|
||||
|
||||
unsubscribeIssues, err := (&issuerpc.Server{Forge: b.issueForge, Allowed: b.managedRepository, Log: log}).Register(coreConn)
|
||||
if err != nil {
|
||||
log.Error("issue RPC register failed", "err", err)
|
||||
return err
|
||||
}
|
||||
b.addCleanup(unsubscribeIssues)
|
||||
return nil
|
||||
}
|
||||
|
||||
// issueForge is the instance forge, or nil while none is configured.
|
||||
func (b *boot) issueForge() forge.IssueForge {
|
||||
if b.forgeClient == nil {
|
||||
return nil
|
||||
}
|
||||
return b.forgeClient
|
||||
}
|
||||
|
||||
// managedRepository refuses a repository the organisation has not added.
|
||||
func (b *boot) managedRepository(ctx context.Context, owner, repo string) error {
|
||||
_, err := b.repositoryBinding(ctx, owner, repo)
|
||||
return err
|
||||
}
|
||||
|
||||
func (b *boot) buildDaemon() {
|
||||
log := b.log
|
||||
b.d = &daemon.Daemon{
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"flag"
|
||||
@@ -8,6 +9,7 @@ import (
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"oras.land/oras-go/v2/errdef"
|
||||
@@ -506,7 +508,11 @@ func rollBackCanary(ctx context.Context, dashboard releaseupdate.CanaryDashboard
|
||||
if err := releaseupdate.Installable(ctx, source, stable); err != nil {
|
||||
return fmt.Errorf("stable %s is not installable, the canary stays on next: %w", stable.Statement.Version, err)
|
||||
}
|
||||
if migrated(ctx, checkout, stable.Statement.Version, failed) {
|
||||
changed, err := migrated(ctx, checkout, stable.Statement.Version, failed)
|
||||
if err != nil {
|
||||
return holdCanary(ctx, dashboard, failed, err.Error(), out)
|
||||
}
|
||||
if changed {
|
||||
return holdCanary(ctx, dashboard, failed, failed+" changed the database schema", out)
|
||||
}
|
||||
if err := dashboard.Follow(ctx, "exact-pin", stable.Statement.Version); err != nil {
|
||||
@@ -527,12 +533,40 @@ func holdCanary(ctx context.Context, dashboard releaseupdate.CanaryDashboard, ve
|
||||
return nil
|
||||
}
|
||||
|
||||
// runGitDiff runs git diff --quiet between two release tags and reports its
|
||||
// exit code and stderr. It is a variable so tests can drive the three
|
||||
// outcomes without a repository.
|
||||
var runGitDiff = func(ctx context.Context, checkout, from, to string) (int, string, error) {
|
||||
cmd := exec.CommandContext(ctx, "git", "-C", checkout, "diff", "--quiet", "v"+from, "v"+to, "--", migrationsDir)
|
||||
var buf bytes.Buffer
|
||||
cmd.Stderr = &buf
|
||||
err := cmd.Run()
|
||||
if err == nil {
|
||||
return 0, "", nil
|
||||
}
|
||||
if exitErr, ok := errors.AsType[*exec.ExitError](err); ok {
|
||||
return exitErr.ExitCode(), buf.String(), err
|
||||
}
|
||||
return -1, buf.String(), err
|
||||
}
|
||||
|
||||
// migrated reports whether the migrations differ between two release tags.
|
||||
// If it can't tell, it says they differ, so the canary is held rather than
|
||||
// rolled back.
|
||||
func migrated(ctx context.Context, checkout, from, to string) bool {
|
||||
err := exec.CommandContext(ctx, "git", "-C", checkout, "diff", "--quiet", "v"+from, "v"+to, "--", migrationsDir).Run()
|
||||
return err != nil
|
||||
// It returns true, nil when they differ, false, nil when they are identical,
|
||||
// and true, err when git could not answer, with the reason in err. Every
|
||||
// non-identical outcome holds the canary rather than rolls it back.
|
||||
func migrated(ctx context.Context, checkout, from, to string) (bool, error) {
|
||||
code, stderr, runErr := runGitDiff(ctx, checkout, from, to)
|
||||
switch code {
|
||||
case 0:
|
||||
return false, nil
|
||||
case 1:
|
||||
return true, nil
|
||||
}
|
||||
reason := strings.TrimSpace(stderr)
|
||||
if reason == "" && runErr != nil {
|
||||
reason = runErr.Error()
|
||||
}
|
||||
return true, fmt.Errorf("could not tell whether %s changed the database schema: %s", to, reason)
|
||||
}
|
||||
|
||||
func runCanaryPromote(args []string, out, stderr io.Writer) int {
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestMigrated(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
code int
|
||||
stderr string
|
||||
wantChanged bool
|
||||
wantErr bool
|
||||
wantSubstr string
|
||||
}{
|
||||
{
|
||||
name: "identical migrations",
|
||||
code: 0,
|
||||
wantChanged: false,
|
||||
},
|
||||
{
|
||||
name: "migrations differ",
|
||||
code: 1,
|
||||
wantChanged: true,
|
||||
},
|
||||
{
|
||||
name: "git cannot answer",
|
||||
code: 128,
|
||||
stderr: "fatal: bad revision 'v1.0.0'\n",
|
||||
wantChanged: true,
|
||||
wantErr: true,
|
||||
wantSubstr: "fatal: bad revision 'v1.0.0'",
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
old := runGitDiff
|
||||
runGitDiff = func(context.Context, string, string, string) (int, string, error) {
|
||||
return tt.code, tt.stderr, nil
|
||||
}
|
||||
t.Cleanup(func() { runGitDiff = old })
|
||||
|
||||
changed, err := migrated(context.Background(), ".", "1.0.0", "1.1.0")
|
||||
if changed != tt.wantChanged {
|
||||
t.Fatalf("changed = %v, want %v", changed, tt.wantChanged)
|
||||
}
|
||||
if (err != nil) != tt.wantErr {
|
||||
t.Fatalf("err = %v, want err %v", err, tt.wantErr)
|
||||
}
|
||||
if tt.wantErr && !strings.Contains(err.Error(), tt.wantSubstr) {
|
||||
t.Fatalf("err = %q, want substring %q", err, tt.wantSubstr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -77,6 +77,13 @@ func (b *boot) removeTaskWorktree(task *taskactions.Task) error {
|
||||
if b.d == nil {
|
||||
return nil
|
||||
}
|
||||
// A run that handed off shares the work item's worktree with its
|
||||
// successor; archiving the old run must not remove it.
|
||||
if current, err := b.stateStore.TaskByIssue(context.Background(), task.Owner, task.Repo, task.IssueNumber); err != nil {
|
||||
return err
|
||||
} else if current != nil && current.ID != task.ID {
|
||||
return nil
|
||||
}
|
||||
return b.d.RemoveWorktree(&workflow.Task{Owner: task.Owner, Repo: task.Repo, Identity: task.Identity, IssueNumber: task.IssueNumber, Org: task.Org})
|
||||
}
|
||||
|
||||
|
||||
@@ -18,6 +18,7 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
infraaccess "github.com/samcharles93/archie-core/internal/infrastructure/access"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/controlplanerpc"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/issuerpc"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/staterpc"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/taskmcp"
|
||||
"github.com/samcharles93/archie-core/internal/plugin"
|
||||
@@ -112,6 +113,11 @@ func (b *server) registerWorkflowTools(ctx context.Context) {
|
||||
// Run-inspection tools back long-running curators (self-intake first);
|
||||
// the State Store client satisfies the source directly.
|
||||
entries = append(entries, gateway.RunTools(b.stateStore, authz)...)
|
||||
// Issue tools reach the forge through the daemon, which alone holds its
|
||||
// credentials; without the broker connection they are not registered.
|
||||
if b.taskActionsConn != nil {
|
||||
entries = append(entries, gateway.IssueTools(issuerpc.Client{Conn: b.taskActionsConn, Timeout: 30 * time.Second}, authz)...)
|
||||
}
|
||||
for _, entry := range entries {
|
||||
if err := b.toolReg.Register(entry); err != nil {
|
||||
b.log.WarnContext(ctx, "workflow tool registration failed", "tool", entry.Name, "err", err)
|
||||
|
||||
@@ -202,6 +202,11 @@ func (b *server) seedAndValidatePolicies(ctx context.Context) error {
|
||||
// not to the sequence that triggers it.
|
||||
func (b *server) reportUnseededResources(skipped []controlplanestore.SeedSkip) {
|
||||
for _, skip := range skipped {
|
||||
if len(skip.Removed) > 0 {
|
||||
b.log.Warn("removed stored entries that no longer validate; their earlier revision is in the resource history",
|
||||
"kind", skip.Kind, "removed", skip.Removed)
|
||||
continue
|
||||
}
|
||||
b.log.Error("control-plane resource not seeded; the kind stays absent and the file's value is the one in effect",
|
||||
"kind", skip.Kind, "err", skip.Err)
|
||||
}
|
||||
|
||||
@@ -2163,6 +2163,110 @@ func (x *EnqueueCallTaskRequest) GetCallKey() string {
|
||||
return ""
|
||||
}
|
||||
|
||||
type HandoffTaskRequest struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
TaskId int64 `protobuf:"varint,1,opt,name=task_id,json=taskId,proto3" json:"task_id,omitempty"`
|
||||
Workflow string `protobuf:"bytes,2,opt,name=workflow,proto3" json:"workflow,omitempty"`
|
||||
Detail string `protobuf:"bytes,3,opt,name=detail,proto3" json:"detail,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *HandoffTaskRequest) Reset() {
|
||||
*x = HandoffTaskRequest{}
|
||||
mi := &file_state_v1_task_proto_msgTypes[41]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *HandoffTaskRequest) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*HandoffTaskRequest) ProtoMessage() {}
|
||||
|
||||
func (x *HandoffTaskRequest) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_state_v1_task_proto_msgTypes[41]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use HandoffTaskRequest.ProtoReflect.Descriptor instead.
|
||||
func (*HandoffTaskRequest) Descriptor() ([]byte, []int) {
|
||||
return file_state_v1_task_proto_rawDescGZIP(), []int{41}
|
||||
}
|
||||
|
||||
func (x *HandoffTaskRequest) GetTaskId() int64 {
|
||||
if x != nil {
|
||||
return x.TaskId
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *HandoffTaskRequest) GetWorkflow() string {
|
||||
if x != nil {
|
||||
return x.Workflow
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *HandoffTaskRequest) GetDetail() string {
|
||||
if x != nil {
|
||||
return x.Detail
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
type HandoffTaskResponse struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Task *Task `protobuf:"bytes,1,opt,name=task,proto3" json:"task,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *HandoffTaskResponse) Reset() {
|
||||
*x = HandoffTaskResponse{}
|
||||
mi := &file_state_v1_task_proto_msgTypes[42]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *HandoffTaskResponse) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*HandoffTaskResponse) ProtoMessage() {}
|
||||
|
||||
func (x *HandoffTaskResponse) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_state_v1_task_proto_msgTypes[42]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use HandoffTaskResponse.ProtoReflect.Descriptor instead.
|
||||
func (*HandoffTaskResponse) Descriptor() ([]byte, []int) {
|
||||
return file_state_v1_task_proto_rawDescGZIP(), []int{42}
|
||||
}
|
||||
|
||||
func (x *HandoffTaskResponse) GetTask() *Task {
|
||||
if x != nil {
|
||||
return x.Task
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type EnqueueCallTaskResponse struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Task *Task `protobuf:"bytes,1,opt,name=task,proto3" json:"task,omitempty"`
|
||||
@@ -2173,7 +2277,7 @@ type EnqueueCallTaskResponse struct {
|
||||
|
||||
func (x *EnqueueCallTaskResponse) Reset() {
|
||||
*x = EnqueueCallTaskResponse{}
|
||||
mi := &file_state_v1_task_proto_msgTypes[41]
|
||||
mi := &file_state_v1_task_proto_msgTypes[43]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
@@ -2185,7 +2289,7 @@ func (x *EnqueueCallTaskResponse) String() string {
|
||||
func (*EnqueueCallTaskResponse) ProtoMessage() {}
|
||||
|
||||
func (x *EnqueueCallTaskResponse) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_state_v1_task_proto_msgTypes[41]
|
||||
mi := &file_state_v1_task_proto_msgTypes[43]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
@@ -2198,7 +2302,7 @@ func (x *EnqueueCallTaskResponse) ProtoReflect() protoreflect.Message {
|
||||
|
||||
// Deprecated: Use EnqueueCallTaskResponse.ProtoReflect.Descriptor instead.
|
||||
func (*EnqueueCallTaskResponse) Descriptor() ([]byte, []int) {
|
||||
return file_state_v1_task_proto_rawDescGZIP(), []int{41}
|
||||
return file_state_v1_task_proto_rawDescGZIP(), []int{43}
|
||||
}
|
||||
|
||||
func (x *EnqueueCallTaskResponse) GetTask() *Task {
|
||||
@@ -2225,7 +2329,7 @@ type WorkflowCallStatusRequest struct {
|
||||
|
||||
func (x *WorkflowCallStatusRequest) Reset() {
|
||||
*x = WorkflowCallStatusRequest{}
|
||||
mi := &file_state_v1_task_proto_msgTypes[42]
|
||||
mi := &file_state_v1_task_proto_msgTypes[44]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
@@ -2237,7 +2341,7 @@ func (x *WorkflowCallStatusRequest) String() string {
|
||||
func (*WorkflowCallStatusRequest) ProtoMessage() {}
|
||||
|
||||
func (x *WorkflowCallStatusRequest) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_state_v1_task_proto_msgTypes[42]
|
||||
mi := &file_state_v1_task_proto_msgTypes[44]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
@@ -2250,7 +2354,7 @@ func (x *WorkflowCallStatusRequest) ProtoReflect() protoreflect.Message {
|
||||
|
||||
// Deprecated: Use WorkflowCallStatusRequest.ProtoReflect.Descriptor instead.
|
||||
func (*WorkflowCallStatusRequest) Descriptor() ([]byte, []int) {
|
||||
return file_state_v1_task_proto_rawDescGZIP(), []int{42}
|
||||
return file_state_v1_task_proto_rawDescGZIP(), []int{44}
|
||||
}
|
||||
|
||||
func (x *WorkflowCallStatusRequest) GetCallerTaskId() int64 {
|
||||
@@ -2283,7 +2387,7 @@ type WorkflowCallStatusResponse struct {
|
||||
|
||||
func (x *WorkflowCallStatusResponse) Reset() {
|
||||
*x = WorkflowCallStatusResponse{}
|
||||
mi := &file_state_v1_task_proto_msgTypes[43]
|
||||
mi := &file_state_v1_task_proto_msgTypes[45]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
@@ -2295,7 +2399,7 @@ func (x *WorkflowCallStatusResponse) String() string {
|
||||
func (*WorkflowCallStatusResponse) ProtoMessage() {}
|
||||
|
||||
func (x *WorkflowCallStatusResponse) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_state_v1_task_proto_msgTypes[43]
|
||||
mi := &file_state_v1_task_proto_msgTypes[45]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
@@ -2308,7 +2412,7 @@ func (x *WorkflowCallStatusResponse) ProtoReflect() protoreflect.Message {
|
||||
|
||||
// Deprecated: Use WorkflowCallStatusResponse.ProtoReflect.Descriptor instead.
|
||||
func (*WorkflowCallStatusResponse) Descriptor() ([]byte, []int) {
|
||||
return file_state_v1_task_proto_rawDescGZIP(), []int{43}
|
||||
return file_state_v1_task_proto_rawDescGZIP(), []int{45}
|
||||
}
|
||||
|
||||
func (x *WorkflowCallStatusResponse) GetStatus() string {
|
||||
@@ -2341,7 +2445,7 @@ type TaskModelsRequest struct {
|
||||
|
||||
func (x *TaskModelsRequest) Reset() {
|
||||
*x = TaskModelsRequest{}
|
||||
mi := &file_state_v1_task_proto_msgTypes[44]
|
||||
mi := &file_state_v1_task_proto_msgTypes[46]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
@@ -2353,7 +2457,7 @@ func (x *TaskModelsRequest) String() string {
|
||||
func (*TaskModelsRequest) ProtoMessage() {}
|
||||
|
||||
func (x *TaskModelsRequest) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_state_v1_task_proto_msgTypes[44]
|
||||
mi := &file_state_v1_task_proto_msgTypes[46]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
@@ -2366,7 +2470,7 @@ func (x *TaskModelsRequest) ProtoReflect() protoreflect.Message {
|
||||
|
||||
// Deprecated: Use TaskModelsRequest.ProtoReflect.Descriptor instead.
|
||||
func (*TaskModelsRequest) Descriptor() ([]byte, []int) {
|
||||
return file_state_v1_task_proto_rawDescGZIP(), []int{44}
|
||||
return file_state_v1_task_proto_rawDescGZIP(), []int{46}
|
||||
}
|
||||
|
||||
func (x *TaskModelsRequest) GetTaskId() int64 {
|
||||
@@ -2385,7 +2489,7 @@ type TaskInstructionsRequest struct {
|
||||
|
||||
func (x *TaskInstructionsRequest) Reset() {
|
||||
*x = TaskInstructionsRequest{}
|
||||
mi := &file_state_v1_task_proto_msgTypes[45]
|
||||
mi := &file_state_v1_task_proto_msgTypes[47]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
@@ -2397,7 +2501,7 @@ func (x *TaskInstructionsRequest) String() string {
|
||||
func (*TaskInstructionsRequest) ProtoMessage() {}
|
||||
|
||||
func (x *TaskInstructionsRequest) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_state_v1_task_proto_msgTypes[45]
|
||||
mi := &file_state_v1_task_proto_msgTypes[47]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
@@ -2410,7 +2514,7 @@ func (x *TaskInstructionsRequest) ProtoReflect() protoreflect.Message {
|
||||
|
||||
// Deprecated: Use TaskInstructionsRequest.ProtoReflect.Descriptor instead.
|
||||
func (*TaskInstructionsRequest) Descriptor() ([]byte, []int) {
|
||||
return file_state_v1_task_proto_rawDescGZIP(), []int{45}
|
||||
return file_state_v1_task_proto_rawDescGZIP(), []int{47}
|
||||
}
|
||||
|
||||
func (x *TaskInstructionsRequest) GetTaskId() int64 {
|
||||
@@ -2430,7 +2534,7 @@ type TaskInstructionsResponse struct {
|
||||
|
||||
func (x *TaskInstructionsResponse) Reset() {
|
||||
*x = TaskInstructionsResponse{}
|
||||
mi := &file_state_v1_task_proto_msgTypes[46]
|
||||
mi := &file_state_v1_task_proto_msgTypes[48]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
@@ -2442,7 +2546,7 @@ func (x *TaskInstructionsResponse) String() string {
|
||||
func (*TaskInstructionsResponse) ProtoMessage() {}
|
||||
|
||||
func (x *TaskInstructionsResponse) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_state_v1_task_proto_msgTypes[46]
|
||||
mi := &file_state_v1_task_proto_msgTypes[48]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
@@ -2455,7 +2559,7 @@ func (x *TaskInstructionsResponse) ProtoReflect() protoreflect.Message {
|
||||
|
||||
// Deprecated: Use TaskInstructionsResponse.ProtoReflect.Descriptor instead.
|
||||
func (*TaskInstructionsResponse) Descriptor() ([]byte, []int) {
|
||||
return file_state_v1_task_proto_rawDescGZIP(), []int{46}
|
||||
return file_state_v1_task_proto_rawDescGZIP(), []int{48}
|
||||
}
|
||||
|
||||
func (x *TaskInstructionsResponse) GetInstance() string {
|
||||
@@ -2483,7 +2587,7 @@ type TaskModelsResponse struct {
|
||||
|
||||
func (x *TaskModelsResponse) Reset() {
|
||||
*x = TaskModelsResponse{}
|
||||
mi := &file_state_v1_task_proto_msgTypes[47]
|
||||
mi := &file_state_v1_task_proto_msgTypes[49]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
@@ -2495,7 +2599,7 @@ func (x *TaskModelsResponse) String() string {
|
||||
func (*TaskModelsResponse) ProtoMessage() {}
|
||||
|
||||
func (x *TaskModelsResponse) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_state_v1_task_proto_msgTypes[47]
|
||||
mi := &file_state_v1_task_proto_msgTypes[49]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
@@ -2508,7 +2612,7 @@ func (x *TaskModelsResponse) ProtoReflect() protoreflect.Message {
|
||||
|
||||
// Deprecated: Use TaskModelsResponse.ProtoReflect.Descriptor instead.
|
||||
func (*TaskModelsResponse) Descriptor() ([]byte, []int) {
|
||||
return file_state_v1_task_proto_rawDescGZIP(), []int{47}
|
||||
return file_state_v1_task_proto_rawDescGZIP(), []int{49}
|
||||
}
|
||||
|
||||
func (x *TaskModelsResponse) GetOrgId() string {
|
||||
@@ -2550,7 +2654,7 @@ type ModelProvider struct {
|
||||
|
||||
func (x *ModelProvider) Reset() {
|
||||
*x = ModelProvider{}
|
||||
mi := &file_state_v1_task_proto_msgTypes[48]
|
||||
mi := &file_state_v1_task_proto_msgTypes[50]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
@@ -2562,7 +2666,7 @@ func (x *ModelProvider) String() string {
|
||||
func (*ModelProvider) ProtoMessage() {}
|
||||
|
||||
func (x *ModelProvider) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_state_v1_task_proto_msgTypes[48]
|
||||
mi := &file_state_v1_task_proto_msgTypes[50]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
@@ -2575,7 +2679,7 @@ func (x *ModelProvider) ProtoReflect() protoreflect.Message {
|
||||
|
||||
// Deprecated: Use ModelProvider.ProtoReflect.Descriptor instead.
|
||||
func (*ModelProvider) Descriptor() ([]byte, []int) {
|
||||
return file_state_v1_task_proto_rawDescGZIP(), []int{48}
|
||||
return file_state_v1_task_proto_rawDescGZIP(), []int{50}
|
||||
}
|
||||
|
||||
func (x *ModelProvider) GetClass() string {
|
||||
@@ -2746,7 +2850,13 @@ const file_state_v1_task_proto_rawDesc = "" +
|
||||
"\bworkflow\x18\x02 \x01(\tR\bworkflow\x12\x1f\n" +
|
||||
"\vinputs_json\x18\x03 \x01(\tR\n" +
|
||||
"inputsJson\x12\x19\n" +
|
||||
"\bcall_key\x18\x04 \x01(\tR\acallKey\"Y\n" +
|
||||
"\bcall_key\x18\x04 \x01(\tR\acallKey\"a\n" +
|
||||
"\x12HandoffTaskRequest\x12\x17\n" +
|
||||
"\atask_id\x18\x01 \x01(\x03R\x06taskId\x12\x1a\n" +
|
||||
"\bworkflow\x18\x02 \x01(\tR\bworkflow\x12\x16\n" +
|
||||
"\x06detail\x18\x03 \x01(\tR\x06detail\"9\n" +
|
||||
"\x13HandoffTaskResponse\x12\"\n" +
|
||||
"\x04task\x18\x01 \x01(\v2\x0e.state.v1.TaskR\x04task\"Y\n" +
|
||||
"\x17EnqueueCallTaskResponse\x12\"\n" +
|
||||
"\x04task\x18\x01 \x01(\v2\x0e.state.v1.TaskR\x04task\x12\x1a\n" +
|
||||
"\baccepted\x18\x02 \x01(\bR\baccepted\"c\n" +
|
||||
@@ -2780,7 +2890,7 @@ const file_state_v1_task_proto_rawDesc = "" +
|
||||
"\bbase_url\x18\x02 \x01(\tR\abaseUrl\x12\x1e\n" +
|
||||
"\vapi_key_env\x18\x03 \x01(\tR\tapiKeyEnv\x12$\n" +
|
||||
"\x0eapi_key_engine\x18\x04 \x01(\tR\fapiKeyEngine\x12\x1e\n" +
|
||||
"\vapi_key_key\x18\x05 \x01(\tR\tapiKeyKey2\xe6\x0e\n" +
|
||||
"\vapi_key_key\x18\x05 \x01(\tR\tapiKeyKey2\xb2\x0f\n" +
|
||||
"\vTaskService\x12M\n" +
|
||||
"\fEnqueueIssue\x12\x1d.state.v1.EnqueueIssueRequest\x1a\x1e.state.v1.EnqueueIssueResponse\x12V\n" +
|
||||
"\x0fEnqueueChatTask\x12 .state.v1.EnqueueChatTaskRequest\x1a!.state.v1.EnqueueChatTaskResponse\x12b\n" +
|
||||
@@ -2806,7 +2916,8 @@ const file_state_v1_task_proto_rawDesc = "" +
|
||||
"\aOpenPRs\x12\x18.state.v1.OpenPRsRequest\x1a\x19.state.v1.OpenPRsResponse\x12_\n" +
|
||||
"\x12ClearTerminalTasks\x12#.state.v1.ClearTerminalTasksRequest\x1a$.state.v1.ClearTerminalTasksResponse\x128\n" +
|
||||
"\x05Tasks\x12\x16.state.v1.TasksRequest\x1a\x17.state.v1.TasksResponse\x12V\n" +
|
||||
"\x0fEnqueueCallTask\x12 .state.v1.EnqueueCallTaskRequest\x1a!.state.v1.EnqueueCallTaskResponse\x12_\n" +
|
||||
"\x0fEnqueueCallTask\x12 .state.v1.EnqueueCallTaskRequest\x1a!.state.v1.EnqueueCallTaskResponse\x12J\n" +
|
||||
"\vHandoffTask\x12\x1c.state.v1.HandoffTaskRequest\x1a\x1d.state.v1.HandoffTaskResponse\x12_\n" +
|
||||
"\x12WorkflowCallStatus\x12#.state.v1.WorkflowCallStatusRequest\x1a$.state.v1.WorkflowCallStatusResponseB\xa3\x01\n" +
|
||||
"\fcom.state.v1B\tTaskProtoP\x01ZGgithub.com/samcharles93/archie-core/internal/contracts/state/v1;statev1\xa2\x02\x03SXX\xaa\x02\bState.V1\xca\x02\bState\\V1\xe2\x02\x14State\\V1\\GPBMetadata\xea\x02\tState::V1b\x06proto3"
|
||||
|
||||
@@ -2822,7 +2933,7 @@ func file_state_v1_task_proto_rawDescGZIP() []byte {
|
||||
return file_state_v1_task_proto_rawDescData
|
||||
}
|
||||
|
||||
var file_state_v1_task_proto_msgTypes = make([]protoimpl.MessageInfo, 51)
|
||||
var file_state_v1_task_proto_msgTypes = make([]protoimpl.MessageInfo, 53)
|
||||
var file_state_v1_task_proto_goTypes = []any{
|
||||
(*EnqueueIssueRequest)(nil), // 0: state.v1.EnqueueIssueRequest
|
||||
(*EnqueueIssueResponse)(nil), // 1: state.v1.EnqueueIssueResponse
|
||||
@@ -2865,91 +2976,96 @@ var file_state_v1_task_proto_goTypes = []any{
|
||||
(*TasksRequest)(nil), // 38: state.v1.TasksRequest
|
||||
(*TasksResponse)(nil), // 39: state.v1.TasksResponse
|
||||
(*EnqueueCallTaskRequest)(nil), // 40: state.v1.EnqueueCallTaskRequest
|
||||
(*EnqueueCallTaskResponse)(nil), // 41: state.v1.EnqueueCallTaskResponse
|
||||
(*WorkflowCallStatusRequest)(nil), // 42: state.v1.WorkflowCallStatusRequest
|
||||
(*WorkflowCallStatusResponse)(nil), // 43: state.v1.WorkflowCallStatusResponse
|
||||
(*TaskModelsRequest)(nil), // 44: state.v1.TaskModelsRequest
|
||||
(*TaskInstructionsRequest)(nil), // 45: state.v1.TaskInstructionsRequest
|
||||
(*TaskInstructionsResponse)(nil), // 46: state.v1.TaskInstructionsResponse
|
||||
(*TaskModelsResponse)(nil), // 47: state.v1.TaskModelsResponse
|
||||
(*ModelProvider)(nil), // 48: state.v1.ModelProvider
|
||||
nil, // 49: state.v1.TaskModelsResponse.AliasesEntry
|
||||
nil, // 50: state.v1.TaskModelsResponse.ProvidersEntry
|
||||
(*Task)(nil), // 51: state.v1.Task
|
||||
(*Event)(nil), // 52: state.v1.Event
|
||||
(*timestamppb.Timestamp)(nil), // 53: google.protobuf.Timestamp
|
||||
(*HandoffTaskRequest)(nil), // 41: state.v1.HandoffTaskRequest
|
||||
(*HandoffTaskResponse)(nil), // 42: state.v1.HandoffTaskResponse
|
||||
(*EnqueueCallTaskResponse)(nil), // 43: state.v1.EnqueueCallTaskResponse
|
||||
(*WorkflowCallStatusRequest)(nil), // 44: state.v1.WorkflowCallStatusRequest
|
||||
(*WorkflowCallStatusResponse)(nil), // 45: state.v1.WorkflowCallStatusResponse
|
||||
(*TaskModelsRequest)(nil), // 46: state.v1.TaskModelsRequest
|
||||
(*TaskInstructionsRequest)(nil), // 47: state.v1.TaskInstructionsRequest
|
||||
(*TaskInstructionsResponse)(nil), // 48: state.v1.TaskInstructionsResponse
|
||||
(*TaskModelsResponse)(nil), // 49: state.v1.TaskModelsResponse
|
||||
(*ModelProvider)(nil), // 50: state.v1.ModelProvider
|
||||
nil, // 51: state.v1.TaskModelsResponse.AliasesEntry
|
||||
nil, // 52: state.v1.TaskModelsResponse.ProvidersEntry
|
||||
(*Task)(nil), // 53: state.v1.Task
|
||||
(*Event)(nil), // 54: state.v1.Event
|
||||
(*timestamppb.Timestamp)(nil), // 55: google.protobuf.Timestamp
|
||||
}
|
||||
var file_state_v1_task_proto_depIdxs = []int32{
|
||||
51, // 0: state.v1.ActiveTasksByOriginResponse.tasks:type_name -> state.v1.Task
|
||||
51, // 1: state.v1.UnpostedOutcomesResponse.tasks:type_name -> state.v1.Task
|
||||
51, // 2: state.v1.EnqueueChatTaskResponse.task:type_name -> state.v1.Task
|
||||
51, // 3: state.v1.ClaimNextResponse.task:type_name -> state.v1.Task
|
||||
51, // 4: state.v1.ClaimByIssueResponse.task:type_name -> state.v1.Task
|
||||
51, // 5: state.v1.UpdateRequest.task:type_name -> state.v1.Task
|
||||
52, // 6: state.v1.ArchiveTaskRequest.audit:type_name -> state.v1.Event
|
||||
51, // 7: state.v1.TaskByIssueResponse.task:type_name -> state.v1.Task
|
||||
51, // 8: state.v1.OpenTaskByPRResponse.task:type_name -> state.v1.Task
|
||||
51, // 9: state.v1.TaskByIDResponse.task:type_name -> state.v1.Task
|
||||
51, // 10: state.v1.OpenPRsResponse.tasks:type_name -> state.v1.Task
|
||||
53, // 11: state.v1.TasksRequest.after_updated_at:type_name -> google.protobuf.Timestamp
|
||||
51, // 12: state.v1.TasksResponse.tasks:type_name -> state.v1.Task
|
||||
51, // 13: state.v1.EnqueueCallTaskResponse.task:type_name -> state.v1.Task
|
||||
49, // 14: state.v1.TaskModelsResponse.aliases:type_name -> state.v1.TaskModelsResponse.AliasesEntry
|
||||
50, // 15: state.v1.TaskModelsResponse.providers:type_name -> state.v1.TaskModelsResponse.ProvidersEntry
|
||||
48, // 16: state.v1.TaskModelsResponse.ProvidersEntry.value:type_name -> state.v1.ModelProvider
|
||||
0, // 17: state.v1.TaskService.EnqueueIssue:input_type -> state.v1.EnqueueIssueRequest
|
||||
8, // 18: state.v1.TaskService.EnqueueChatTask:input_type -> state.v1.EnqueueChatTaskRequest
|
||||
2, // 19: state.v1.TaskService.ActiveTasksByOrigin:input_type -> state.v1.ActiveTasksByOriginRequest
|
||||
4, // 20: state.v1.TaskService.UnpostedOutcomes:input_type -> state.v1.UnpostedOutcomesRequest
|
||||
6, // 21: state.v1.TaskService.MarkOutcomePosted:input_type -> state.v1.MarkOutcomePostedRequest
|
||||
10, // 22: state.v1.TaskService.ClaimNext:input_type -> state.v1.ClaimNextRequest
|
||||
12, // 23: state.v1.TaskService.ClaimByIssue:input_type -> state.v1.ClaimByIssueRequest
|
||||
14, // 24: state.v1.TaskService.Transition:input_type -> state.v1.TransitionRequest
|
||||
16, // 25: state.v1.TaskService.Update:input_type -> state.v1.UpdateRequest
|
||||
44, // 26: state.v1.TaskService.TaskModels:input_type -> state.v1.TaskModelsRequest
|
||||
45, // 27: state.v1.TaskService.TaskInstructions:input_type -> state.v1.TaskInstructionsRequest
|
||||
18, // 28: state.v1.TaskService.Requeue:input_type -> state.v1.RequeueRequest
|
||||
20, // 29: state.v1.TaskService.ParkTask:input_type -> state.v1.ParkTaskRequest
|
||||
22, // 30: state.v1.TaskService.RecoverStale:input_type -> state.v1.RecoverStaleRequest
|
||||
24, // 31: state.v1.TaskService.ArchiveTask:input_type -> state.v1.ArchiveTaskRequest
|
||||
26, // 32: state.v1.TaskService.RetryTask:input_type -> state.v1.RetryTaskRequest
|
||||
28, // 33: state.v1.TaskService.TaskByIssue:input_type -> state.v1.TaskByIssueRequest
|
||||
30, // 34: state.v1.TaskService.OpenTaskByPR:input_type -> state.v1.OpenTaskByPRRequest
|
||||
32, // 35: state.v1.TaskService.TaskByID:input_type -> state.v1.TaskByIDRequest
|
||||
34, // 36: state.v1.TaskService.OpenPRs:input_type -> state.v1.OpenPRsRequest
|
||||
36, // 37: state.v1.TaskService.ClearTerminalTasks:input_type -> state.v1.ClearTerminalTasksRequest
|
||||
38, // 38: state.v1.TaskService.Tasks:input_type -> state.v1.TasksRequest
|
||||
40, // 39: state.v1.TaskService.EnqueueCallTask:input_type -> state.v1.EnqueueCallTaskRequest
|
||||
42, // 40: state.v1.TaskService.WorkflowCallStatus:input_type -> state.v1.WorkflowCallStatusRequest
|
||||
1, // 41: state.v1.TaskService.EnqueueIssue:output_type -> state.v1.EnqueueIssueResponse
|
||||
9, // 42: state.v1.TaskService.EnqueueChatTask:output_type -> state.v1.EnqueueChatTaskResponse
|
||||
3, // 43: state.v1.TaskService.ActiveTasksByOrigin:output_type -> state.v1.ActiveTasksByOriginResponse
|
||||
5, // 44: state.v1.TaskService.UnpostedOutcomes:output_type -> state.v1.UnpostedOutcomesResponse
|
||||
7, // 45: state.v1.TaskService.MarkOutcomePosted:output_type -> state.v1.MarkOutcomePostedResponse
|
||||
11, // 46: state.v1.TaskService.ClaimNext:output_type -> state.v1.ClaimNextResponse
|
||||
13, // 47: state.v1.TaskService.ClaimByIssue:output_type -> state.v1.ClaimByIssueResponse
|
||||
15, // 48: state.v1.TaskService.Transition:output_type -> state.v1.TransitionResponse
|
||||
17, // 49: state.v1.TaskService.Update:output_type -> state.v1.UpdateResponse
|
||||
47, // 50: state.v1.TaskService.TaskModels:output_type -> state.v1.TaskModelsResponse
|
||||
46, // 51: state.v1.TaskService.TaskInstructions:output_type -> state.v1.TaskInstructionsResponse
|
||||
19, // 52: state.v1.TaskService.Requeue:output_type -> state.v1.RequeueResponse
|
||||
21, // 53: state.v1.TaskService.ParkTask:output_type -> state.v1.ParkTaskResponse
|
||||
23, // 54: state.v1.TaskService.RecoverStale:output_type -> state.v1.RecoverStaleResponse
|
||||
25, // 55: state.v1.TaskService.ArchiveTask:output_type -> state.v1.ArchiveTaskResponse
|
||||
27, // 56: state.v1.TaskService.RetryTask:output_type -> state.v1.RetryTaskResponse
|
||||
29, // 57: state.v1.TaskService.TaskByIssue:output_type -> state.v1.TaskByIssueResponse
|
||||
31, // 58: state.v1.TaskService.OpenTaskByPR:output_type -> state.v1.OpenTaskByPRResponse
|
||||
33, // 59: state.v1.TaskService.TaskByID:output_type -> state.v1.TaskByIDResponse
|
||||
35, // 60: state.v1.TaskService.OpenPRs:output_type -> state.v1.OpenPRsResponse
|
||||
37, // 61: state.v1.TaskService.ClearTerminalTasks:output_type -> state.v1.ClearTerminalTasksResponse
|
||||
39, // 62: state.v1.TaskService.Tasks:output_type -> state.v1.TasksResponse
|
||||
41, // 63: state.v1.TaskService.EnqueueCallTask:output_type -> state.v1.EnqueueCallTaskResponse
|
||||
43, // 64: state.v1.TaskService.WorkflowCallStatus:output_type -> state.v1.WorkflowCallStatusResponse
|
||||
41, // [41:65] is the sub-list for method output_type
|
||||
17, // [17:41] is the sub-list for method input_type
|
||||
17, // [17:17] is the sub-list for extension type_name
|
||||
17, // [17:17] is the sub-list for extension extendee
|
||||
0, // [0:17] is the sub-list for field type_name
|
||||
53, // 0: state.v1.ActiveTasksByOriginResponse.tasks:type_name -> state.v1.Task
|
||||
53, // 1: state.v1.UnpostedOutcomesResponse.tasks:type_name -> state.v1.Task
|
||||
53, // 2: state.v1.EnqueueChatTaskResponse.task:type_name -> state.v1.Task
|
||||
53, // 3: state.v1.ClaimNextResponse.task:type_name -> state.v1.Task
|
||||
53, // 4: state.v1.ClaimByIssueResponse.task:type_name -> state.v1.Task
|
||||
53, // 5: state.v1.UpdateRequest.task:type_name -> state.v1.Task
|
||||
54, // 6: state.v1.ArchiveTaskRequest.audit:type_name -> state.v1.Event
|
||||
53, // 7: state.v1.TaskByIssueResponse.task:type_name -> state.v1.Task
|
||||
53, // 8: state.v1.OpenTaskByPRResponse.task:type_name -> state.v1.Task
|
||||
53, // 9: state.v1.TaskByIDResponse.task:type_name -> state.v1.Task
|
||||
53, // 10: state.v1.OpenPRsResponse.tasks:type_name -> state.v1.Task
|
||||
55, // 11: state.v1.TasksRequest.after_updated_at:type_name -> google.protobuf.Timestamp
|
||||
53, // 12: state.v1.TasksResponse.tasks:type_name -> state.v1.Task
|
||||
53, // 13: state.v1.HandoffTaskResponse.task:type_name -> state.v1.Task
|
||||
53, // 14: state.v1.EnqueueCallTaskResponse.task:type_name -> state.v1.Task
|
||||
51, // 15: state.v1.TaskModelsResponse.aliases:type_name -> state.v1.TaskModelsResponse.AliasesEntry
|
||||
52, // 16: state.v1.TaskModelsResponse.providers:type_name -> state.v1.TaskModelsResponse.ProvidersEntry
|
||||
50, // 17: state.v1.TaskModelsResponse.ProvidersEntry.value:type_name -> state.v1.ModelProvider
|
||||
0, // 18: state.v1.TaskService.EnqueueIssue:input_type -> state.v1.EnqueueIssueRequest
|
||||
8, // 19: state.v1.TaskService.EnqueueChatTask:input_type -> state.v1.EnqueueChatTaskRequest
|
||||
2, // 20: state.v1.TaskService.ActiveTasksByOrigin:input_type -> state.v1.ActiveTasksByOriginRequest
|
||||
4, // 21: state.v1.TaskService.UnpostedOutcomes:input_type -> state.v1.UnpostedOutcomesRequest
|
||||
6, // 22: state.v1.TaskService.MarkOutcomePosted:input_type -> state.v1.MarkOutcomePostedRequest
|
||||
10, // 23: state.v1.TaskService.ClaimNext:input_type -> state.v1.ClaimNextRequest
|
||||
12, // 24: state.v1.TaskService.ClaimByIssue:input_type -> state.v1.ClaimByIssueRequest
|
||||
14, // 25: state.v1.TaskService.Transition:input_type -> state.v1.TransitionRequest
|
||||
16, // 26: state.v1.TaskService.Update:input_type -> state.v1.UpdateRequest
|
||||
46, // 27: state.v1.TaskService.TaskModels:input_type -> state.v1.TaskModelsRequest
|
||||
47, // 28: state.v1.TaskService.TaskInstructions:input_type -> state.v1.TaskInstructionsRequest
|
||||
18, // 29: state.v1.TaskService.Requeue:input_type -> state.v1.RequeueRequest
|
||||
20, // 30: state.v1.TaskService.ParkTask:input_type -> state.v1.ParkTaskRequest
|
||||
22, // 31: state.v1.TaskService.RecoverStale:input_type -> state.v1.RecoverStaleRequest
|
||||
24, // 32: state.v1.TaskService.ArchiveTask:input_type -> state.v1.ArchiveTaskRequest
|
||||
26, // 33: state.v1.TaskService.RetryTask:input_type -> state.v1.RetryTaskRequest
|
||||
28, // 34: state.v1.TaskService.TaskByIssue:input_type -> state.v1.TaskByIssueRequest
|
||||
30, // 35: state.v1.TaskService.OpenTaskByPR:input_type -> state.v1.OpenTaskByPRRequest
|
||||
32, // 36: state.v1.TaskService.TaskByID:input_type -> state.v1.TaskByIDRequest
|
||||
34, // 37: state.v1.TaskService.OpenPRs:input_type -> state.v1.OpenPRsRequest
|
||||
36, // 38: state.v1.TaskService.ClearTerminalTasks:input_type -> state.v1.ClearTerminalTasksRequest
|
||||
38, // 39: state.v1.TaskService.Tasks:input_type -> state.v1.TasksRequest
|
||||
40, // 40: state.v1.TaskService.EnqueueCallTask:input_type -> state.v1.EnqueueCallTaskRequest
|
||||
41, // 41: state.v1.TaskService.HandoffTask:input_type -> state.v1.HandoffTaskRequest
|
||||
44, // 42: state.v1.TaskService.WorkflowCallStatus:input_type -> state.v1.WorkflowCallStatusRequest
|
||||
1, // 43: state.v1.TaskService.EnqueueIssue:output_type -> state.v1.EnqueueIssueResponse
|
||||
9, // 44: state.v1.TaskService.EnqueueChatTask:output_type -> state.v1.EnqueueChatTaskResponse
|
||||
3, // 45: state.v1.TaskService.ActiveTasksByOrigin:output_type -> state.v1.ActiveTasksByOriginResponse
|
||||
5, // 46: state.v1.TaskService.UnpostedOutcomes:output_type -> state.v1.UnpostedOutcomesResponse
|
||||
7, // 47: state.v1.TaskService.MarkOutcomePosted:output_type -> state.v1.MarkOutcomePostedResponse
|
||||
11, // 48: state.v1.TaskService.ClaimNext:output_type -> state.v1.ClaimNextResponse
|
||||
13, // 49: state.v1.TaskService.ClaimByIssue:output_type -> state.v1.ClaimByIssueResponse
|
||||
15, // 50: state.v1.TaskService.Transition:output_type -> state.v1.TransitionResponse
|
||||
17, // 51: state.v1.TaskService.Update:output_type -> state.v1.UpdateResponse
|
||||
49, // 52: state.v1.TaskService.TaskModels:output_type -> state.v1.TaskModelsResponse
|
||||
48, // 53: state.v1.TaskService.TaskInstructions:output_type -> state.v1.TaskInstructionsResponse
|
||||
19, // 54: state.v1.TaskService.Requeue:output_type -> state.v1.RequeueResponse
|
||||
21, // 55: state.v1.TaskService.ParkTask:output_type -> state.v1.ParkTaskResponse
|
||||
23, // 56: state.v1.TaskService.RecoverStale:output_type -> state.v1.RecoverStaleResponse
|
||||
25, // 57: state.v1.TaskService.ArchiveTask:output_type -> state.v1.ArchiveTaskResponse
|
||||
27, // 58: state.v1.TaskService.RetryTask:output_type -> state.v1.RetryTaskResponse
|
||||
29, // 59: state.v1.TaskService.TaskByIssue:output_type -> state.v1.TaskByIssueResponse
|
||||
31, // 60: state.v1.TaskService.OpenTaskByPR:output_type -> state.v1.OpenTaskByPRResponse
|
||||
33, // 61: state.v1.TaskService.TaskByID:output_type -> state.v1.TaskByIDResponse
|
||||
35, // 62: state.v1.TaskService.OpenPRs:output_type -> state.v1.OpenPRsResponse
|
||||
37, // 63: state.v1.TaskService.ClearTerminalTasks:output_type -> state.v1.ClearTerminalTasksResponse
|
||||
39, // 64: state.v1.TaskService.Tasks:output_type -> state.v1.TasksResponse
|
||||
43, // 65: state.v1.TaskService.EnqueueCallTask:output_type -> state.v1.EnqueueCallTaskResponse
|
||||
42, // 66: state.v1.TaskService.HandoffTask:output_type -> state.v1.HandoffTaskResponse
|
||||
45, // 67: state.v1.TaskService.WorkflowCallStatus:output_type -> state.v1.WorkflowCallStatusResponse
|
||||
43, // [43:68] is the sub-list for method output_type
|
||||
18, // [18:43] is the sub-list for method input_type
|
||||
18, // [18:18] is the sub-list for extension type_name
|
||||
18, // [18:18] is the sub-list for extension extendee
|
||||
0, // [0:18] is the sub-list for field type_name
|
||||
}
|
||||
|
||||
func init() { file_state_v1_task_proto_init() }
|
||||
@@ -2964,7 +3080,7 @@ func file_state_v1_task_proto_init() {
|
||||
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
|
||||
RawDescriptor: unsafe.Slice(unsafe.StringData(file_state_v1_task_proto_rawDesc), len(file_state_v1_task_proto_rawDesc)),
|
||||
NumEnums: 0,
|
||||
NumMessages: 51,
|
||||
NumMessages: 53,
|
||||
NumExtensions: 0,
|
||||
NumServices: 1,
|
||||
},
|
||||
|
||||
@@ -42,6 +42,7 @@ const (
|
||||
TaskService_ClearTerminalTasks_FullMethodName = "/state.v1.TaskService/ClearTerminalTasks"
|
||||
TaskService_Tasks_FullMethodName = "/state.v1.TaskService/Tasks"
|
||||
TaskService_EnqueueCallTask_FullMethodName = "/state.v1.TaskService/EnqueueCallTask"
|
||||
TaskService_HandoffTask_FullMethodName = "/state.v1.TaskService/HandoffTask"
|
||||
TaskService_WorkflowCallStatus_FullMethodName = "/state.v1.TaskService/WorkflowCallStatus"
|
||||
)
|
||||
|
||||
@@ -84,6 +85,9 @@ type TaskServiceClient interface {
|
||||
// (docs/prds/workflow-calls.md). CallStatus re-checks the parent-child
|
||||
// relation server-side, so the grant only names the caller.
|
||||
EnqueueCallTask(ctx context.Context, in *EnqueueCallTaskRequest, opts ...grpc.CallOption) (*EnqueueCallTaskResponse, error)
|
||||
// HandoffTask completes a running run and starts its linked successor on
|
||||
// the same work item under another workflow.
|
||||
HandoffTask(ctx context.Context, in *HandoffTaskRequest, opts ...grpc.CallOption) (*HandoffTaskResponse, error)
|
||||
WorkflowCallStatus(ctx context.Context, in *WorkflowCallStatusRequest, opts ...grpc.CallOption) (*WorkflowCallStatusResponse, error)
|
||||
}
|
||||
|
||||
@@ -325,6 +329,16 @@ func (c *taskServiceClient) EnqueueCallTask(ctx context.Context, in *EnqueueCall
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *taskServiceClient) HandoffTask(ctx context.Context, in *HandoffTaskRequest, opts ...grpc.CallOption) (*HandoffTaskResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(HandoffTaskResponse)
|
||||
err := c.cc.Invoke(ctx, TaskService_HandoffTask_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *taskServiceClient) WorkflowCallStatus(ctx context.Context, in *WorkflowCallStatusRequest, opts ...grpc.CallOption) (*WorkflowCallStatusResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(WorkflowCallStatusResponse)
|
||||
@@ -374,6 +388,9 @@ type TaskServiceServer interface {
|
||||
// (docs/prds/workflow-calls.md). CallStatus re-checks the parent-child
|
||||
// relation server-side, so the grant only names the caller.
|
||||
EnqueueCallTask(context.Context, *EnqueueCallTaskRequest) (*EnqueueCallTaskResponse, error)
|
||||
// HandoffTask completes a running run and starts its linked successor on
|
||||
// the same work item under another workflow.
|
||||
HandoffTask(context.Context, *HandoffTaskRequest) (*HandoffTaskResponse, error)
|
||||
WorkflowCallStatus(context.Context, *WorkflowCallStatusRequest) (*WorkflowCallStatusResponse, error)
|
||||
mustEmbedUnimplementedTaskServiceServer()
|
||||
}
|
||||
@@ -454,6 +471,9 @@ func (UnimplementedTaskServiceServer) Tasks(context.Context, *TasksRequest) (*Ta
|
||||
func (UnimplementedTaskServiceServer) EnqueueCallTask(context.Context, *EnqueueCallTaskRequest) (*EnqueueCallTaskResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method EnqueueCallTask not implemented")
|
||||
}
|
||||
func (UnimplementedTaskServiceServer) HandoffTask(context.Context, *HandoffTaskRequest) (*HandoffTaskResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method HandoffTask not implemented")
|
||||
}
|
||||
func (UnimplementedTaskServiceServer) WorkflowCallStatus(context.Context, *WorkflowCallStatusRequest) (*WorkflowCallStatusResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method WorkflowCallStatus not implemented")
|
||||
}
|
||||
@@ -892,6 +912,24 @@ func _TaskService_EnqueueCallTask_Handler(srv interface{}, ctx context.Context,
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _TaskService_HandoffTask_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(HandoffTaskRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(TaskServiceServer).HandoffTask(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: TaskService_HandoffTask_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(TaskServiceServer).HandoffTask(ctx, req.(*HandoffTaskRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _TaskService_WorkflowCallStatus_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(WorkflowCallStatusRequest)
|
||||
if err := dec(in); err != nil {
|
||||
@@ -1009,6 +1047,10 @@ var TaskService_ServiceDesc = grpc.ServiceDesc{
|
||||
MethodName: "EnqueueCallTask",
|
||||
Handler: _TaskService_EnqueueCallTask_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "HandoffTask",
|
||||
Handler: _TaskService_HandoffTask_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "WorkflowCallStatus",
|
||||
Handler: _TaskService_WorkflowCallStatus_Handler,
|
||||
|
||||
@@ -229,9 +229,13 @@ type Task struct {
|
||||
// recorded at the park site; empty when the park has no known fix.
|
||||
ParkBlocker string `protobuf:"bytes,48,opt,name=park_blocker,json=parkBlocker,proto3" json:"park_blocker,omitempty"`
|
||||
// plan_document is the structured plan (JSON) plan was rendered from.
|
||||
PlanDocument string `protobuf:"bytes,50,opt,name=plan_document,json=planDocument,proto3" json:"plan_document,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
PlanDocument string `protobuf:"bytes,50,opt,name=plan_document,json=planDocument,proto3" json:"plan_document,omitempty"`
|
||||
// handoff_from_task_id is the run that handed off to this one; 0 when none.
|
||||
HandoffFromTaskId int64 `protobuf:"varint,51,opt,name=handoff_from_task_id,json=handoffFromTaskId,proto3" json:"handoff_from_task_id,omitempty"`
|
||||
// handoff_to_task_id is the run this one handed off to; 0 when none.
|
||||
HandoffToTaskId int64 `protobuf:"varint,52,opt,name=handoff_to_task_id,json=handoffToTaskId,proto3" json:"handoff_to_task_id,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *Task) Reset() {
|
||||
@@ -608,6 +612,20 @@ func (x *Task) GetPlanDocument() string {
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *Task) GetHandoffFromTaskId() int64 {
|
||||
if x != nil {
|
||||
return x.HandoffFromTaskId
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *Task) GetHandoffToTaskId() int64 {
|
||||
if x != nil {
|
||||
return x.HandoffToTaskId
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// Event mirrors internal/events.Event. Data is carried as a JSON object
|
||||
// string (matching the store's own on-disk representation) rather than
|
||||
// google.protobuf.Struct, to stay a direct mirror of the existing column.
|
||||
@@ -784,7 +802,7 @@ const file_state_v1_types_proto_rawDesc = "" +
|
||||
"\n" +
|
||||
"created_at\x18\x06 \x01(\v2\x1a.google.protobuf.TimestampR\tcreatedAt\x129\n" +
|
||||
"\n" +
|
||||
"updated_at\x18\a \x01(\v2\x1a.google.protobuf.TimestampR\tupdatedAt\"\x91\r\n" +
|
||||
"updated_at\x18\a \x01(\v2\x1a.google.protobuf.TimestampR\tupdatedAt\"\xef\r\n" +
|
||||
"\x04Task\x12\x0e\n" +
|
||||
"\x02id\x18\x01 \x01(\x03R\x02id\x12\x14\n" +
|
||||
"\x05owner\x18\x02 \x01(\tR\x05owner\x12\x12\n" +
|
||||
@@ -849,7 +867,9 @@ const file_state_v1_types_proto_rawDesc = "" +
|
||||
"\x11binding_signature\x18. \x01(\tR\x10bindingSignature\x12!\n" +
|
||||
"\fbinding_addr\x18/ \x01(\tR\vbindingAddr\x12!\n" +
|
||||
"\fpark_blocker\x180 \x01(\tR\vparkBlocker\x12#\n" +
|
||||
"\rplan_document\x182 \x01(\tR\fplanDocumentJ\x04\b1\x102R\tplan_view\"\xf8\x02\n" +
|
||||
"\rplan_document\x182 \x01(\tR\fplanDocument\x12/\n" +
|
||||
"\x14handoff_from_task_id\x183 \x01(\x03R\x11handoffFromTaskId\x12+\n" +
|
||||
"\x12handoff_to_task_id\x184 \x01(\x03R\x0fhandoffToTaskIdJ\x04\b1\x102R\tplan_view\"\xf8\x02\n" +
|
||||
"\x05Event\x12\x0e\n" +
|
||||
"\x02id\x18\x01 \x01(\x03R\x02id\x12*\n" +
|
||||
"\x02at\x18\x02 \x01(\v2\x1a.google.protobuf.TimestampR\x02at\x12\x12\n" +
|
||||
|
||||
@@ -1753,7 +1753,9 @@ func (d *Daemon) cleanupTerminalTaskWorktree(ctx context.Context, task *workflow
|
||||
d.Log.WarnContext(ctx, "terminal worktree cleanup task lookup failed", "task", task.ID, "err", err)
|
||||
return
|
||||
}
|
||||
if latest == nil {
|
||||
// A run that handed off shares its work item's worktree with its
|
||||
// successor, which owns it from here.
|
||||
if latest == nil || latest.HandoffToTaskID != 0 {
|
||||
return
|
||||
}
|
||||
// Settled statuses. Keep the worktree while a PR exists.
|
||||
|
||||
@@ -76,7 +76,7 @@ func mustKey(encoded string) ed25519.PublicKey {
|
||||
func DefaultCatalogue() Source {
|
||||
return Source{
|
||||
Reference: "git.catlow.cloud/sam/archipelago/catalogue",
|
||||
Key: mustKey("YL4nvn07uq/5mXZOt9cEmLYu/kB6C2+MLTnbHyoX4Pw="),
|
||||
Key: mustKey("PLouShOzvRqy1QbYaJplaM41/ulgKFN8ZQ7g1rI02Fc="),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -36,8 +36,8 @@ type handoffSettings struct {
|
||||
Detail string `yaml:"detail" doc:"Why the task was handed off."`
|
||||
}
|
||||
|
||||
// newHandoffStage requeues the task under another workflow: the same task,
|
||||
// not a child run, so its history stays in one place.
|
||||
// newHandoffStage completes the run and starts a linked run of another
|
||||
// workflow on the same work item.
|
||||
func newHandoffStage(settings yaml.Node) (Stage, error) {
|
||||
s, err := decodeSettings[handoffSettings](HandoffStepName, settings)
|
||||
if err != nil {
|
||||
@@ -47,8 +47,7 @@ func newHandoffStage(settings yaml.Node) (Stage, error) {
|
||||
return Stage{}, fmt.Errorf("%s: settings.workflow is required", HandoffStepName)
|
||||
}
|
||||
return Stage{Name: HandoffStepName, Run: func(_ context.Context, tc *TaskContext) error {
|
||||
tc.Task.Workflow = strings.TrimSpace(s.Workflow)
|
||||
tc.Outcome = Outcome{Status: StatusQueued, Detail: s.Detail}
|
||||
tc.Outcome = Outcome{Status: StatusCompleted, Detail: s.Detail, Handoff: strings.TrimSpace(s.Workflow)}
|
||||
return nil
|
||||
}}, nil
|
||||
}
|
||||
|
||||
@@ -387,3 +387,37 @@ func hasStepType(node any, types []string) bool {
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// RepairDefinitionCollection rebuilds a stored collection that no longer
|
||||
// validates, keeping every entry it can: a valid entry is kept, an invalid
|
||||
// shipped entry is replaced by this build's copy, and any other invalid or
|
||||
// duplicate entry is removed and its id returned. An unreadable document or a
|
||||
// repair that still fails validation is an error.
|
||||
func RepairDefinitionCollection(value []byte, registry StepRegistry) (WorkflowDefinitionCollection, []string, error) {
|
||||
var stored WorkflowDefinitionCollection
|
||||
if err := json.Unmarshal(value, &stored); err != nil {
|
||||
return WorkflowDefinitionCollection{}, nil, err
|
||||
}
|
||||
shipped := ShippedDefinitions()
|
||||
seen := make(map[string]struct{}, len(stored.Definitions))
|
||||
var repaired WorkflowDefinitionCollection
|
||||
var removed []string
|
||||
for _, entry := range stored.Definitions {
|
||||
if _, dup := seen[entry.ID]; dup {
|
||||
removed = append(removed, entry.ID)
|
||||
continue
|
||||
}
|
||||
seen[entry.ID] = struct{}{}
|
||||
if definition, err := ParseDefinition(entry.YAML, registry); err == nil && definition.ID == entry.ID {
|
||||
repaired.Definitions = append(repaired.Definitions, entry)
|
||||
} else if factory, ok := shipped.DefinitionByID(entry.ID); ok {
|
||||
repaired.Definitions = append(repaired.Definitions, factory)
|
||||
} else {
|
||||
removed = append(removed, entry.ID)
|
||||
}
|
||||
}
|
||||
if err := ValidateDefinitionCollection(repaired, registry); err != nil {
|
||||
return WorkflowDefinitionCollection{}, nil, err
|
||||
}
|
||||
return repaired, removed, nil
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package workflow
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// A stored collection that stopped validating keeps every entry it can: valid
|
||||
// entries stay, a broken shipped entry is restored, a broken custom one goes.
|
||||
func TestRepairDefinitionCollection(t *testing.T) {
|
||||
shipped, _ := ShippedDefinitions().DefinitionByID("triage")
|
||||
custom := strings.Replace(shipped.YAML, "id: triage", "id: mine", 1)
|
||||
edited := shipped.YAML + "\n# edited by the operator\n"
|
||||
broken := "id: broken\nsteps:\n - id: a\n type: removed.step\n"
|
||||
// with is the shipped set with triage's YAML swapped and extra appended.
|
||||
with := func(triage string, extra ...WorkflowDefinitionEntry) ([]WorkflowDefinitionEntry, map[string]string) {
|
||||
entries, byID := []WorkflowDefinitionEntry{}, map[string]string{}
|
||||
for _, entry := range ShippedDefinitions().Definitions {
|
||||
if entry.ID == "triage" {
|
||||
entry.YAML = triage
|
||||
}
|
||||
entries = append(entries, entry)
|
||||
byID[entry.ID] = entry.YAML
|
||||
}
|
||||
for _, entry := range extra {
|
||||
entries = append(entries, entry)
|
||||
byID[entry.ID] = entry.YAML
|
||||
}
|
||||
return entries, byID
|
||||
}
|
||||
restoredStored, _ := with(broken, WorkflowDefinitionEntry{ID: "mine", YAML: custom})
|
||||
_, restoredWant := with(shipped.YAML, WorkflowDefinitionEntry{ID: "mine", YAML: custom})
|
||||
editedStored, _ := with(edited, WorkflowDefinitionEntry{ID: "broken", YAML: broken})
|
||||
_, editedWant := with(edited)
|
||||
tests := []struct {
|
||||
name string
|
||||
stored []WorkflowDefinitionEntry
|
||||
want map[string]string
|
||||
wantRemoved []string
|
||||
}{
|
||||
{
|
||||
name: "broken shipped entry is restored, custom kept",
|
||||
stored: restoredStored,
|
||||
want: restoredWant,
|
||||
},
|
||||
{
|
||||
name: "broken custom entry is removed, edited shipped kept",
|
||||
stored: editedStored,
|
||||
want: editedWant,
|
||||
wantRemoved: []string{"broken"},
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
value, err := json.Marshal(WorkflowDefinitionCollection{Definitions: tt.stored})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, removed, err := RepairDefinitionCollection(value, triageRegistry())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
byID := map[string]string{}
|
||||
for _, entry := range got.Definitions {
|
||||
byID[entry.ID] = entry.YAML
|
||||
}
|
||||
if len(byID) != len(tt.want) {
|
||||
t.Fatalf("kept %d entries, want %d", len(byID), len(tt.want))
|
||||
}
|
||||
for id, yaml := range tt.want {
|
||||
if byID[id] != yaml {
|
||||
t.Errorf("entry %q not kept as expected", id)
|
||||
}
|
||||
}
|
||||
if !slices.Equal(removed, tt.wantRemoved) {
|
||||
t.Errorf("removed %v, want %v", removed, tt.wantRemoved)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -113,7 +113,7 @@ func runRepoTooling(ctx context.Context, tc *TaskContext) error {
|
||||
}
|
||||
|
||||
type repoCommitSettings struct {
|
||||
Message string `yaml:"message" doc:"The commit message."`
|
||||
Message string `yaml:"message" doc:"The commit message. Hooks in the checkout never run, so commit-message policy (commitlint, DCO) is not applied."`
|
||||
// Reference is the verb that links the commit to the task's issue
|
||||
// ("Fixes", "Implements", "Refs"); empty links nothing.
|
||||
Reference string `yaml:"reference" enum:"Fixes,Implements,Refs" doc:"How the commit links to the task issue."`
|
||||
|
||||
@@ -16,4 +16,8 @@ type Caller interface {
|
||||
// call_parent_task_id is callerTaskID, so a caller reads only its own
|
||||
// callees.
|
||||
CallStatus(ctx context.Context, callerTaskID, callTaskID int64) (status, detail string, outputs map[string]any, err error)
|
||||
// Handoff completes the running task fromTaskID with detail and starts
|
||||
// its linked successor on the same work item under workflow, returning
|
||||
// the successor.
|
||||
Handoff(ctx context.Context, fromTaskID int64, workflow, detail string) (*Task, error)
|
||||
}
|
||||
@@ -141,6 +141,10 @@ type Task struct {
|
||||
// one; 0 on a root run. A caller reads only the tasks it started,
|
||||
// through WorkflowCallStatus.
|
||||
CallParentTaskID int64 `json:"call_parent_task_id,omitempty"`
|
||||
// HandoffFromTaskID is the run whose workflow.handoff started this one,
|
||||
// and HandoffToTaskID the run this one handed off to; 0 when none.
|
||||
HandoffFromTaskID int64 `json:"handoff_from_task_id,omitempty"`
|
||||
HandoffToTaskID int64 `json:"handoff_to_task_id,omitempty"`
|
||||
// CallDepth counts workflow.call hops from the root run. The engine
|
||||
// refuses a call past workflow.MaxCallDepth, and the store re-checks on
|
||||
// insert, so no enqueue path can pass the limit.
|
||||
|
||||
@@ -279,6 +279,9 @@ func transcriptData(entry agentrun.TranscriptEntry) (map[string]any, error) {
|
||||
type Outcome struct {
|
||||
Status string // Status* value; empty = continue to next stage
|
||||
Detail string // park reason / close rationale / PR body context
|
||||
// Handoff names the workflow a linked successor run starts under once
|
||||
// this run completes; empty starts none.
|
||||
Handoff string
|
||||
}
|
||||
|
||||
// Stage is one named step. Returning an error parks the task with the
|
||||
@@ -507,6 +510,26 @@ func publishEvent(ctx context.Context, tc *TaskContext, e events.Event) {
|
||||
tc.Bus.Publish(ctx, e)
|
||||
}
|
||||
|
||||
// handoff completes the run and starts its linked successor in one store
|
||||
// write, so the work item keeps exactly one current run.
|
||||
func handoff(ctx context.Context, tc *TaskContext, log *slog.Logger) {
|
||||
if tc.Calls == nil {
|
||||
park(ctx, tc, "workflow.handoff: this runner cannot start a linked run")
|
||||
return
|
||||
}
|
||||
next, err := tc.Calls.Handoff(ctx, tc.Task.ID, tc.Outcome.Handoff, tc.Outcome.Detail)
|
||||
if err != nil {
|
||||
log.ErrorContext(ctx, "workflow handoff failed", "err", err)
|
||||
park(ctx, tc, fmt.Sprintf("workflow.handoff to %s: %v", tc.Outcome.Handoff, err))
|
||||
return
|
||||
}
|
||||
tc.Task.HandoffToTaskID = next.ID
|
||||
tc.Emit(ctx, events.KindOutcome, tc.Stage, tc.Outcome.Detail, map[string]any{
|
||||
"status": tc.Outcome.Status, "handoff_task_id": next.ID, "workflow": tc.Outcome.Handoff,
|
||||
})
|
||||
log.InfoContext(ctx, "workflow handed off", "workflow", tc.Outcome.Handoff, "task", next.ID)
|
||||
}
|
||||
|
||||
func finish(ctx context.Context, tc *TaskContext, log *slog.Logger) {
|
||||
t := tc.Task
|
||||
if tc.Outcome.Status == StatusParked {
|
||||
@@ -525,6 +548,10 @@ func finish(ctx context.Context, tc *TaskContext, log *slog.Logger) {
|
||||
park(ctx, tc, fmt.Sprintf("persist workflow outcome: %v", err))
|
||||
return
|
||||
}
|
||||
if tc.Outcome.Handoff != "" {
|
||||
handoff(ctx, tc, log)
|
||||
return
|
||||
}
|
||||
if err := tc.Store.Transition(ctx, t.ID, StatusRunning, tc.Outcome.Status, tc.Outcome.Detail); err != nil {
|
||||
log.ErrorContext(ctx, "workflow outcome transition failed", "err", err)
|
||||
return
|
||||
|
||||
@@ -37,6 +37,10 @@ func (c *callSpy) StartCall(_ context.Context, callerTaskID int64, callKey, _ st
|
||||
return child, nil
|
||||
}
|
||||
|
||||
func (c *callSpy) Handoff(context.Context, int64, string, string) (*task.Task, error) {
|
||||
return nil, errors.New("no handoff")
|
||||
}
|
||||
|
||||
func (c *callSpy) CallStatus(context.Context, int64, int64) (string, string, map[string]any, error) {
|
||||
return StatusCompleted, "", nil, nil
|
||||
}
|
||||
@@ -384,6 +388,10 @@ func (c *wobblyCaller) StartCall(_ context.Context, callerTaskID int64, _, _ str
|
||||
return &task.Task{ID: 42, CallParentTaskID: callerTaskID}, nil
|
||||
}
|
||||
|
||||
func (c *wobblyCaller) Handoff(context.Context, int64, string, string) (*task.Task, error) {
|
||||
return nil, errors.New("no handoff")
|
||||
}
|
||||
|
||||
func (c *wobblyCaller) CallStatus(context.Context, int64, int64) (string, string, map[string]any, error) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/access"
|
||||
"github.com/samcharles93/archie-core/internal/forge"
|
||||
"github.com/samcharles93/archie-core/internal/tools"
|
||||
)
|
||||
|
||||
// maxIssueListed bounds what issue_list returns, so a large backlog does not
|
||||
// land in the context window whole.
|
||||
const maxIssueListed = 200
|
||||
|
||||
// IssueSource is the forge surface the issue tools use, reached through the
|
||||
// daemon.
|
||||
type IssueSource interface {
|
||||
OpenIssues(ctx context.Context, owner, repo string) ([]forge.Issue, error)
|
||||
CreateIssue(ctx context.Context, owner, repo, title, body string, labels []string) (int, error)
|
||||
}
|
||||
|
||||
// IssueSummary is one open issue as issue_list shows it.
|
||||
type IssueSummary struct {
|
||||
Number int `json:"number"`
|
||||
Title string `json:"title"`
|
||||
Labels []string `json:"labels,omitempty"`
|
||||
}
|
||||
|
||||
// IssueTools returns issue_list and issue_create for curators. Filing work
|
||||
// feeds the daemon's issue intake, so both are checked as acting on tasks.
|
||||
// Nil source or authorizer registers none.
|
||||
func IssueTools(source IssueSource, authz access.Authorizer) []tools.ToolEntry {
|
||||
if source == nil || authz == nil {
|
||||
return nil
|
||||
}
|
||||
return []tools.ToolEntry{
|
||||
guarded(authz, access.ActionRead, access.KindTask, nil, issueListTool(source)),
|
||||
guarded(authz, access.ActionCreate, access.KindTask, nil, issueCreateTool(source)),
|
||||
}
|
||||
}
|
||||
|
||||
var repoProperty = map[string]any{
|
||||
"type": "string",
|
||||
"description": "The repository as owner/name, as run_list reports it.",
|
||||
}
|
||||
|
||||
func splitRepo(input map[string]any) (owner, repo string, err error) {
|
||||
raw, _ := input["repo"].(string)
|
||||
owner, repo, ok := strings.Cut(strings.TrimSpace(raw), "/")
|
||||
if !ok || owner == "" || repo == "" || strings.Contains(repo, "/") {
|
||||
return "", "", fmt.Errorf("repo must be owner/name")
|
||||
}
|
||||
return owner, repo, nil
|
||||
}
|
||||
|
||||
func issueListTool(source IssueSource) tools.ToolEntry {
|
||||
return tools.ToolEntry{
|
||||
Name: "issue_list",
|
||||
Toolset: "issues",
|
||||
Description: "List a repository's open issues (number, title, labels). Check it before filing so you never duplicate one.",
|
||||
Classification: tools.ClassIdempotent,
|
||||
Schema: tools.JSONSchema{
|
||||
"type": "object",
|
||||
"properties": map[string]any{"repo": repoProperty},
|
||||
"required": []string{"repo"},
|
||||
},
|
||||
Handler: func(ctx context.Context, input map[string]any) (any, error) {
|
||||
owner, repo, err := splitRepo(input)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("issue_list: %w", err)
|
||||
}
|
||||
issues, err := source.OpenIssues(ctx, owner, repo)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("issue_list: %w", err)
|
||||
}
|
||||
out := make([]IssueSummary, 0, min(len(issues), maxIssueListed))
|
||||
for _, is := range issues[:min(len(issues), maxIssueListed)] {
|
||||
out = append(out, IssueSummary{Number: is.Number, Title: is.Title, Labels: is.Labels})
|
||||
}
|
||||
return out, nil
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func issueCreateTool(source IssueSource) tools.ToolEntry {
|
||||
return tools.ToolEntry{
|
||||
Name: "issue_create",
|
||||
Toolset: "issues",
|
||||
Description: "File a new issue in a repository. List open issues first and file only work no open issue covers. " +
|
||||
"The body must cite the run that produced it.",
|
||||
Classification: tools.ClassMutating,
|
||||
Schema: tools.JSONSchema{
|
||||
"type": "object",
|
||||
"properties": map[string]any{
|
||||
"repo": repoProperty,
|
||||
"title": map[string]any{"type": "string"},
|
||||
"body": map[string]any{"type": "string"},
|
||||
"labels": map[string]any{"type": "array", "items": map[string]any{"type": "string"}},
|
||||
},
|
||||
"required": []string{"repo", "title", "body"},
|
||||
},
|
||||
Handler: func(ctx context.Context, input map[string]any) (any, error) {
|
||||
owner, repo, err := splitRepo(input)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("issue_create: %w", err)
|
||||
}
|
||||
title, _ := input["title"].(string)
|
||||
body, _ := input["body"].(string)
|
||||
if strings.TrimSpace(title) == "" || strings.TrimSpace(body) == "" {
|
||||
return nil, fmt.Errorf("issue_create: title and body are required")
|
||||
}
|
||||
var labels []string
|
||||
if raw, ok := input["labels"].([]any); ok {
|
||||
for _, l := range raw {
|
||||
if s, ok := l.(string); ok && s != "" {
|
||||
labels = append(labels, s)
|
||||
}
|
||||
}
|
||||
}
|
||||
number, err := source.CreateIssue(ctx, owner, repo, title, body, labels)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("issue_create: %w", err)
|
||||
}
|
||||
return map[string]any{"number": number}, nil
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -193,6 +193,12 @@ func (d deadlineCaller) StartCall(ctx context.Context, callerTaskID int64, callK
|
||||
return d.Caller.StartCall(ctx, callerTaskID, callKey, wf, inputs)
|
||||
}
|
||||
|
||||
func (d deadlineCaller) Handoff(ctx context.Context, fromTaskID int64, wf, detail string) (*task.Task, error) {
|
||||
ctx, cancel := d.withDeadline(ctx)
|
||||
defer cancel()
|
||||
return d.Caller.Handoff(ctx, fromTaskID, wf, detail)
|
||||
}
|
||||
|
||||
func (d deadlineCaller) CallStatus(ctx context.Context, callerTaskID, callTaskID int64) (string, string, map[string]any, error) {
|
||||
ctx, cancel := d.withDeadline(ctx)
|
||||
defer cancel()
|
||||
|
||||
@@ -221,7 +221,7 @@ func (s *Server) resource(ctx context.Context, orgID, kind string) (storecontrac
|
||||
}
|
||||
return resource, err
|
||||
}
|
||||
if _, err := s.seedKind(ctx, orgID, s.definitions[kind], config.Config{}); err != nil && !errors.Is(err, storecontract.ErrResourceVersionConflict) {
|
||||
if _, _, err := s.seedKind(ctx, orgID, s.definitions[kind], config.Config{}); err != nil && !errors.Is(err, storecontract.ErrResourceVersionConflict) {
|
||||
return storecontract.Resource{}, err
|
||||
}
|
||||
return s.store.Resource(ctx, orgID, kind)
|
||||
|
||||
@@ -28,6 +28,10 @@ type Definition struct {
|
||||
// Defaults is the factory value clients offer as "restore shipped". Only
|
||||
// resources that ship with content set it.
|
||||
Defaults func() any
|
||||
// Repair rebuilds a stored value this build no longer accepts, keeping what
|
||||
// it can, and names what it removed. Nil means an invalid stored value of a
|
||||
// shipped kind is replaced by the seed.
|
||||
Repair func(stored []byte) (value []byte, removed []string, err error)
|
||||
// SchemaExtensions are merged into the derived schema's top level, for
|
||||
// vocabulary the document type alone cannot express.
|
||||
SchemaExtensions map[string]any
|
||||
@@ -73,6 +77,9 @@ func (d Definition) Decode(input []byte) ([]byte, error) {
|
||||
type SeedSkip struct {
|
||||
Kind string
|
||||
Err error
|
||||
// Removed names entries a repair dropped from a stored value; Err is nil
|
||||
// then, because the kind was written.
|
||||
Removed []string
|
||||
}
|
||||
|
||||
// seedActor is the audit identity seeds write under.
|
||||
@@ -89,7 +96,10 @@ func (s *Server) ImportConfig(ctx context.Context, cfg config.Config) (map[strin
|
||||
versions := make(map[string]int64, len(s.ordered))
|
||||
var skipped []SeedSkip
|
||||
for _, definition := range s.ordered {
|
||||
version, err := s.seedKind(ctx, storecontract.DefaultOrgID, definition, cfg)
|
||||
version, removed, err := s.seedKind(ctx, storecontract.DefaultOrgID, definition, cfg)
|
||||
if len(removed) > 0 {
|
||||
skipped = append(skipped, SeedSkip{Kind: definition.Kind, Removed: removed})
|
||||
}
|
||||
var refusal *seedRefusal
|
||||
switch {
|
||||
case errors.As(err, &refusal):
|
||||
@@ -108,9 +118,13 @@ func (s *Server) ImportConfig(ctx context.Context, cfg config.Config) (map[strin
|
||||
if resource.OrgID == storecontract.DefaultOrgID || resource.Kind != WorkflowDefinitionsKind {
|
||||
continue
|
||||
}
|
||||
if _, err := s.seedKind(ctx, resource.OrgID, s.definitions[resource.Kind], config.Config{}); err != nil {
|
||||
_, removed, err := s.seedKind(ctx, resource.OrgID, s.definitions[resource.Kind], config.Config{})
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if len(removed) > 0 {
|
||||
skipped = append(skipped, SeedSkip{Kind: resource.Kind, Removed: removed})
|
||||
}
|
||||
}
|
||||
return versions, skipped, nil
|
||||
}
|
||||
@@ -127,30 +141,32 @@ func (r *seedRefusal) Unwrap() error { return r.err }
|
||||
|
||||
// seedKind seeds, refreshes or leaves one kind and returns its version. A
|
||||
// *seedRefusal means the seed failed validation and nothing was written.
|
||||
func (s *Server) seedKind(ctx context.Context, orgID string, definition Definition, cfg config.Config) (int64, error) {
|
||||
func (s *Server) seedKind(ctx context.Context, orgID string, definition Definition, cfg config.Config) (int64, []string, error) {
|
||||
stored, storedErr := s.store.Resource(ctx, orgID, definition.Kind)
|
||||
absent := errors.Is(storedErr, storecontract.ErrResourceNotFound)
|
||||
if storedErr != nil && !absent {
|
||||
return 0, storedErr
|
||||
return 0, nil, storedErr
|
||||
}
|
||||
value, err := definition.seededValue(cfg)
|
||||
if err != nil {
|
||||
// Skipped, not fatal.
|
||||
return 0, &seedRefusal{err: err}
|
||||
return 0, nil, &seedRefusal{err: err}
|
||||
}
|
||||
if !absent && bytes.Equal(stored.Value, value) {
|
||||
// The store already holds what this build seeds. Comparing the values
|
||||
// rather than re-writing them is what keeps a boot from adding a
|
||||
// revision for a document that did not change.
|
||||
return stored.Version, nil
|
||||
return stored.Version, nil, nil
|
||||
}
|
||||
var removed []string
|
||||
if !absent {
|
||||
refresh, err := s.shippedValueIsStale(ctx, orgID, definition)
|
||||
var keep bool
|
||||
value, removed, keep, err = s.replacement(ctx, orgID, definition, stored.Value, value)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
return 0, nil, err
|
||||
}
|
||||
if !refresh {
|
||||
return stored.Version, nil
|
||||
if keep {
|
||||
return stored.Version, nil, nil
|
||||
}
|
||||
}
|
||||
write := storecontract.ResourceWrite{
|
||||
@@ -161,9 +177,29 @@ func (s *Server) seedKind(ctx context.Context, orgID string, definition Definiti
|
||||
}
|
||||
resource, err := s.store.PutResource(ctx, write)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("seed %s: %w", definition.Kind, err)
|
||||
return 0, nil, fmt.Errorf("seed %s: %w", definition.Kind, err)
|
||||
}
|
||||
return resource.Version, nil
|
||||
return resource.Version, removed, nil
|
||||
}
|
||||
|
||||
// replacement decides what a seed writes over a stored value: nothing (keep),
|
||||
// a repair of it, or the seeded value. A failed repair falls back to the seed:
|
||||
// an invalid stored value breaks every reader, so keeping it protects nothing.
|
||||
func (s *Server) replacement(ctx context.Context, orgID string, definition Definition, stored, seeded []byte) ([]byte, []string, bool, error) {
|
||||
replace, err := s.storedValueIsReplaced(ctx, orgID, definition, stored)
|
||||
if err != nil {
|
||||
return nil, nil, false, err
|
||||
}
|
||||
if !replace {
|
||||
return nil, nil, true, nil
|
||||
}
|
||||
if definition.Repair == nil || definition.accepts(stored) {
|
||||
return seeded, nil, false, nil
|
||||
}
|
||||
if repaired, removed, err := definition.Repair(stored); err == nil {
|
||||
return repaired, removed, false, nil
|
||||
}
|
||||
return seeded, nil, false, nil
|
||||
}
|
||||
|
||||
// expectedVersion is the optimistic-concurrency guard a seed writes under: the
|
||||
@@ -175,15 +211,24 @@ func expectedVersion(stored storecontract.Resource, absent bool) int64 {
|
||||
return stored.Version
|
||||
}
|
||||
|
||||
// shippedValueIsStale reports whether the newest stored revision of a
|
||||
// shipped document was written by the seed.
|
||||
func (s *Server) shippedValueIsStale(ctx context.Context, orgID string, definition Definition) (bool, error) {
|
||||
// storedValueIsReplaced reports whether a stored shipped document is rewritten
|
||||
// at seed: the seed wrote it, or this build no longer accepts it.
|
||||
func (s *Server) storedValueIsReplaced(ctx context.Context, orgID string, definition Definition, stored []byte) (bool, error) {
|
||||
if definition.Defaults == nil {
|
||||
return false, nil
|
||||
}
|
||||
if !definition.accepts(stored) {
|
||||
return true, nil
|
||||
}
|
||||
return s.seedWroteNewest(ctx, orgID, definition.Kind)
|
||||
}
|
||||
|
||||
// accepts reports whether input decodes under this build's validator.
|
||||
func (d Definition) accepts(input []byte) bool {
|
||||
_, err := d.Decode(input)
|
||||
return err == nil
|
||||
}
|
||||
|
||||
// seedWroteNewest reports whether the newest revision of kind was written by a
|
||||
// seed. It reads the ledger rather than the current row because the ledger is
|
||||
// what records who wrote a value, and the row does not.
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
package controlplanestore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
)
|
||||
|
||||
type memStore struct {
|
||||
resource storecontract.Resource
|
||||
history []storecontract.Resource
|
||||
}
|
||||
|
||||
func (m *memStore) ListResources(context.Context) ([]storecontract.Resource, error) {
|
||||
return []storecontract.Resource{m.resource}, nil
|
||||
}
|
||||
|
||||
func (m *memStore) Resource(context.Context, string, string) (storecontract.Resource, error) {
|
||||
return m.resource, nil
|
||||
}
|
||||
|
||||
func (m *memStore) ResourceHistory(context.Context, string, string, int) ([]storecontract.Resource, error) {
|
||||
return m.history, nil
|
||||
}
|
||||
|
||||
func (m *memStore) PutResource(_ context.Context, w storecontract.ResourceWrite) (storecontract.Resource, error) {
|
||||
m.resource = storecontract.Resource{OrgID: w.OrgID, Kind: w.Kind, Value: w.Value, Version: m.resource.Version + 1}
|
||||
return m.resource, nil
|
||||
}
|
||||
|
||||
// A shipped document an operator edited is kept, unless it no longer validates:
|
||||
// then it is repaired, or replaced by the build's copy when it has no repair.
|
||||
func TestSeedRefreshesStoredShippedDocumentOnlyWhenInvalid(t *testing.T) {
|
||||
definition := Definition{
|
||||
Kind: "shipped",
|
||||
Seed: func(config.Config) any { return "current" },
|
||||
Defaults: func() any { return "current" },
|
||||
Validate: func(in []byte) error {
|
||||
if string(in) != `"current"` && string(in) != `"edited"` {
|
||||
return errors.New("names a deleted step type")
|
||||
}
|
||||
return nil
|
||||
},
|
||||
}
|
||||
repair := func([]byte) ([]byte, []string, error) { return []byte(`"edited"`), []string{"gone"}, nil }
|
||||
tests := []struct {
|
||||
name string
|
||||
stored string
|
||||
repair func([]byte) ([]byte, []string, error)
|
||||
want string
|
||||
wantRemoved []string
|
||||
}{
|
||||
{"edited and valid is kept", `"edited"`, repair, `"edited"`, nil},
|
||||
{"invalid is repaired", `"deleted-step"`, repair, `"edited"`, []string{"gone"}},
|
||||
{"invalid without a repair is replaced", `"deleted-step"`, nil, `"current"`, nil},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
store := &memStore{
|
||||
resource: storecontract.Resource{Kind: "shipped", Value: []byte(tt.stored), Version: 3},
|
||||
history: []storecontract.Resource{{Actor: "operator", Source: "dashboard"}},
|
||||
}
|
||||
s := &Server{store: store}
|
||||
definition.Repair = tt.repair
|
||||
_, removed, err := s.seedKind(context.Background(), storecontract.DefaultOrgID, definition, config.Config{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !slices.Equal(removed, tt.wantRemoved) {
|
||||
t.Fatalf("removed %v, want %v", removed, tt.wantRemoved)
|
||||
}
|
||||
if got := string(store.resource.Value); got != tt.want {
|
||||
t.Fatalf("stored %s, want %s", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -37,6 +37,14 @@ func workflowDefinitionsDefinition(steps workflow.StepRegistry, settings map[str
|
||||
_, err := workflow.DecodeDefinitionCollection(input, steps)
|
||||
return err
|
||||
},
|
||||
Repair: func(stored []byte) ([]byte, []string, error) {
|
||||
collection, removed, err := workflow.RepairDefinitionCollection(stored, steps)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
value, err := json.Marshal(collection)
|
||||
return value, removed, err
|
||||
},
|
||||
SchemaExtensions: map[string]any{"x-step-types": stepTypeVocabulary(steps, settings), "x-intake-routes": workflow.IntakeRoutes()},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,11 @@ package gatewayrpc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
@@ -12,6 +16,7 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/domain/identity"
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
"github.com/samcharles93/archie-core/internal/domain/taskactions"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/alertwebhook"
|
||||
"github.com/samcharles93/archie-core/internal/taskstate"
|
||||
)
|
||||
|
||||
@@ -21,6 +26,8 @@ type server struct {
|
||||
sessions messaging.SessionStore
|
||||
catalog Catalog
|
||||
asks pendingAsks
|
||||
// fetch reads the head of a URL-only attachment; it reaches public hosts only.
|
||||
fetch *http.Client
|
||||
}
|
||||
|
||||
// RegisterServer serves the Gateway chat contract. catalog supplies the
|
||||
@@ -28,7 +35,7 @@ type server struct {
|
||||
// reload) the dashboard reads over the same contract; a zero Catalog answers
|
||||
// empty lists and an Unavailable reload.
|
||||
func RegisterServer(registrar grpc.ServiceRegistrar, chat messaging.ChatContract, sessions messaging.SessionStore, catalog Catalog) {
|
||||
pb.RegisterChatServiceServer(registrar, &server{chat: chat, sessions: sessions, catalog: catalog})
|
||||
pb.RegisterChatServiceServer(registrar, &server{chat: chat, sessions: sessions, catalog: catalog, fetch: alertwebhook.PublicClient()})
|
||||
}
|
||||
|
||||
func (s *server) sessionStore() (messaging.SessionStore, error) {
|
||||
@@ -72,7 +79,7 @@ func (s *server) RecentTurns(ctx context.Context, r *pb.RecentTurnsRequest) (*pb
|
||||
|
||||
func (s *server) Route(ctx context.Context, r *pb.RouteRequest) (*pb.RouteResponse, error) {
|
||||
in := inboundValue(r.Message)
|
||||
if err := checkInbound(in); err != nil {
|
||||
if err := checkInbound(ctx, s.fetch, in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
v, err := s.chat.Route(ctx, in)
|
||||
@@ -267,7 +274,7 @@ func (s *server) Stream(r *pb.StreamRequest, out grpc.ServerStreamingServer[pb.S
|
||||
}
|
||||
ctx := withAsks(out.Context(), r, remoteAsker{pending: &s.asks, send: send})
|
||||
in := inboundValue(r.Message)
|
||||
if err := checkInbound(in); err != nil {
|
||||
if err := checkInbound(ctx, s.fetch, in); err != nil {
|
||||
return err
|
||||
}
|
||||
events, err := s.chat.Stream(ctx, in)
|
||||
@@ -295,11 +302,54 @@ func (s *server) Answer(_ context.Context, r *pb.AnswerRequest) (*pb.AnswerRespo
|
||||
|
||||
// checkInbound refuses a self-contradicting attachment at the one seam every
|
||||
// channel, in-tree or extension, crosses before the Gateway acts on it.
|
||||
func checkInbound(in messaging.Inbound) error {
|
||||
func checkInbound(ctx context.Context, fetch *http.Client, in messaging.Inbound) error {
|
||||
for _, m := range in.Media {
|
||||
if err := messaging.ValidateInbound(m); err != nil {
|
||||
m, err := withHead(ctx, fetch, m)
|
||||
if err == nil {
|
||||
err = messaging.ValidateInbound(m)
|
||||
}
|
||||
if err != nil {
|
||||
return status.Error(codes.InvalidArgument, err.Error())
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// sniffBytes is enough to recognise an image or a clip container.
|
||||
const sniffBytes = 512
|
||||
|
||||
// withHead gives a URL-only attachment of a sniffed type the first bytes of what
|
||||
// its URL serves, so the type check sees the content rather than the claim. An
|
||||
// unreadable URL is an error: the model provider would fetch it unchecked. The
|
||||
// copy is for validation only; the attachment keeps no bytes.
|
||||
func withHead(ctx context.Context, fetch *http.Client, m messaging.MediaAttachment) (messaging.MediaAttachment, error) {
|
||||
switch m.Type {
|
||||
case messaging.MediaTypeImage, messaging.MediaTypeAudio, messaging.MediaTypeVoice:
|
||||
default:
|
||||
return m, nil
|
||||
}
|
||||
if len(m.Data) > 0 || m.URL == "" {
|
||||
return m, nil
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
|
||||
defer cancel()
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, m.URL, nil)
|
||||
if err != nil {
|
||||
return m, fmt.Errorf("%s attachment URL: %w", m.Type, err)
|
||||
}
|
||||
req.Header.Set("Range", fmt.Sprintf("bytes=0-%d", sniffBytes-1))
|
||||
resp, err := fetch.Do(req)
|
||||
if err != nil {
|
||||
return m, fmt.Errorf("%s attachment URL is unreadable: %w", m.Type, err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusPartialContent {
|
||||
return m, fmt.Errorf("%s attachment URL answered %s", m.Type, resp.Status)
|
||||
}
|
||||
head, err := io.ReadAll(io.LimitReader(resp.Body, sniffBytes))
|
||||
if err != nil || len(head) == 0 {
|
||||
return m, fmt.Errorf("%s attachment URL served no content", m.Type)
|
||||
}
|
||||
m.Data = head
|
||||
return m, nil
|
||||
}
|
||||
@@ -1,6 +1,9 @@
|
||||
package gatewayrpc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"google.golang.org/grpc/codes"
|
||||
@@ -22,18 +25,36 @@ func TestChatWireKeepsGatewayInputs(t *testing.T) {
|
||||
// TestCheckInboundRefusesContradictoryMedia pins that a channel extension
|
||||
// cannot deliver an attachment whose declared type its bytes contradict.
|
||||
func TestCheckInboundRefusesContradictoryMedia(t *testing.T) {
|
||||
// The URL-only rows are served from a local host, which the production
|
||||
// client refuses, so the test client is a plain one.
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/png":
|
||||
_, _ = w.Write([]byte("\x89PNG\r\n\x1a\n"))
|
||||
case "/html":
|
||||
_, _ = w.Write([]byte("<!doctype html><script>"))
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
tests := []struct {
|
||||
name string
|
||||
att messaging.MediaAttachment
|
||||
want codes.Code
|
||||
}{
|
||||
{"a url-only png", messaging.MediaAttachment{Type: messaging.MediaTypeImage, MIMEType: "image/png", URL: srv.URL + "/png"}, codes.OK},
|
||||
{"a url-only png that serves html", messaging.MediaAttachment{Type: messaging.MediaTypeImage, MIMEType: "image/png", URL: srv.URL + "/html"}, codes.InvalidArgument},
|
||||
{"a url-only voice note that serves html", messaging.MediaAttachment{Type: messaging.MediaTypeVoice, MIMEType: "audio/ogg", URL: srv.URL + "/html"}, codes.InvalidArgument},
|
||||
{"a url-only image that cannot be read", messaging.MediaAttachment{Type: messaging.MediaTypeImage, MIMEType: "image/png", URL: srv.URL + "/gone"}, codes.InvalidArgument},
|
||||
{"a url-only document is not fetched", messaging.MediaAttachment{Type: messaging.MediaTypeDocument, MIMEType: "application/pdf", URL: srv.URL + "/html"}, codes.OK},
|
||||
{"a png", messaging.MediaAttachment{Type: messaging.MediaTypeImage, MIMEType: "image/png", Data: []byte("\x89PNG\r\n\x1a\n")}, codes.OK},
|
||||
{"html declared as png", messaging.MediaAttachment{Type: messaging.MediaTypeImage, MIMEType: "image/png", Data: []byte("<!doctype html><script>")}, codes.InvalidArgument},
|
||||
{"an executable declared as png", messaging.MediaAttachment{Type: messaging.MediaTypeImage, MIMEType: "image/png", Data: []byte("\x7fELF\x02\x01\x01\x00")}, codes.InvalidArgument},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got := status.Code(checkInbound(messaging.Inbound{Media: []messaging.MediaAttachment{tt.att}}))
|
||||
got := status.Code(checkInbound(context.Background(), srv.Client(), messaging.Inbound{Media: []messaging.MediaAttachment{tt.att}}))
|
||||
if got != tt.want {
|
||||
t.Fatalf("code = %v, want %v", got, tt.want)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
// Package issuerpc lets the Gateway's curators list and file issues through
|
||||
// the daemon, which alone holds forge credentials.
|
||||
package issuerpc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"github.com/nats-io/nats.go"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/forge"
|
||||
"github.com/samcharles93/archie-core/internal/natsrpc"
|
||||
)
|
||||
|
||||
const (
|
||||
listSubject = "archie.gateway.issue-list"
|
||||
createSubject = "archie.gateway.issue-create"
|
||||
)
|
||||
|
||||
type request struct {
|
||||
Owner string `json:"owner"`
|
||||
Repo string `json:"repo"`
|
||||
Title string `json:"title,omitempty"`
|
||||
Body string `json:"body,omitempty"`
|
||||
Labels []string `json:"labels,omitempty"`
|
||||
}
|
||||
|
||||
type listResponse struct {
|
||||
natsrpc.Envelope
|
||||
Issues []forge.Issue `json:"issues,omitempty"`
|
||||
}
|
||||
|
||||
type createResponse struct {
|
||||
natsrpc.Envelope
|
||||
Number int `json:"number,omitempty"`
|
||||
}
|
||||
|
||||
// Server is the daemon side. Forge returns the instance forge, or nil while
|
||||
// none is configured; Allowed refuses a repository the instance does not manage.
|
||||
type Server struct {
|
||||
Forge func() forge.IssueForge
|
||||
Allowed func(ctx context.Context, owner, repo string) error
|
||||
Log *slog.Logger
|
||||
}
|
||||
|
||||
func (s *Server) forge(ctx context.Context, req request) (forge.IssueForge, error) {
|
||||
if err := s.Allowed(ctx, req.Owner, req.Repo); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
f := s.Forge()
|
||||
if f == nil {
|
||||
return nil, errors.New("forge is not configured")
|
||||
}
|
||||
return f, nil
|
||||
}
|
||||
|
||||
// Register serves the issue subjects on nc.
|
||||
func (s *Server) Register(nc *nats.Conn) (func(), error) {
|
||||
return natsrpc.RegisterAll(nc, []natsrpc.Registration{
|
||||
{Subject: listSubject, Handler: func(ctx context.Context, msg *nats.Msg) {
|
||||
var req request
|
||||
if err := json.Unmarshal(msg.Data, &req); err != nil {
|
||||
natsrpc.Respond(msg, s.Log, "issuerpc", listResponse{Envelope: natsrpc.NewEnvelope(err)})
|
||||
return
|
||||
}
|
||||
f, err := s.forge(ctx, req)
|
||||
var issues []forge.Issue
|
||||
if err == nil {
|
||||
issues, err = f.IssuesWithLabel(ctx, req.Owner, req.Repo, "")
|
||||
}
|
||||
natsrpc.Respond(msg, s.Log, "issuerpc", listResponse{Envelope: natsrpc.NewEnvelope(err), Issues: issues})
|
||||
}},
|
||||
{Subject: createSubject, Handler: func(ctx context.Context, msg *nats.Msg) {
|
||||
var req request
|
||||
if err := json.Unmarshal(msg.Data, &req); err != nil {
|
||||
natsrpc.Respond(msg, s.Log, "issuerpc", createResponse{Envelope: natsrpc.NewEnvelope(err)})
|
||||
return
|
||||
}
|
||||
f, err := s.forge(ctx, req)
|
||||
var number int
|
||||
if err == nil {
|
||||
number, err = f.CreateIssue(ctx, req.Owner, req.Repo, req.Title, req.Body, req.Labels)
|
||||
}
|
||||
natsrpc.Respond(msg, s.Log, "issuerpc", createResponse{Envelope: natsrpc.NewEnvelope(err), Number: number})
|
||||
}},
|
||||
})
|
||||
}
|
||||
|
||||
// Client is the Gateway side.
|
||||
type Client struct {
|
||||
Conn *nats.Conn
|
||||
Timeout time.Duration
|
||||
}
|
||||
|
||||
func (c Client) rpc() *natsrpc.Client { return &natsrpc.Client{Conn: c.Conn, Timeout: c.Timeout} }
|
||||
|
||||
// OpenIssues lists every open issue (not PR) of owner/repo.
|
||||
func (c Client) OpenIssues(ctx context.Context, owner, repo string) ([]forge.Issue, error) {
|
||||
resp, err := natsrpc.Call[listResponse](ctx, c.rpc(), listSubject, request{Owner: owner, Repo: repo})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := resp.Err(); err != nil {
|
||||
return nil, fmt.Errorf("list issues: %w", err)
|
||||
}
|
||||
return resp.Issues, nil
|
||||
}
|
||||
|
||||
// CreateIssue files an issue and returns its number.
|
||||
func (c Client) CreateIssue(ctx context.Context, owner, repo, title, body string, labels []string) (int, error) {
|
||||
resp, err := natsrpc.Call[createResponse](ctx, c.rpc(), createSubject, request{Owner: owner, Repo: repo, Title: title, Body: body, Labels: labels})
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if err := resp.Err(); err != nil {
|
||||
return 0, fmt.Errorf("create issue: %w", err)
|
||||
}
|
||||
return resp.Number, nil
|
||||
}
|
||||
@@ -31,11 +31,16 @@ import (
|
||||
// the tool_calls transcript the composition projection writes through.
|
||||
var (
|
||||
_ storecontract.CaptureStore = (*EDA)(nil)
|
||||
_ storecontract.CaptureRefusalStore = (*EDA)(nil)
|
||||
_ storecontract.MappingStore = (*EDA)(nil)
|
||||
_ storecontract.BindingStore = (*EDA)(nil)
|
||||
_ storecontract.BindingDispatcher = (*EDA)(nil)
|
||||
_ storecontract.MappingMatchRecorder = (*EDA)(nil)
|
||||
_ storecontract.EventTypeStore = (*EDA)(nil)
|
||||
_ storecontract.BindingStore = (*EDA)(nil)
|
||||
_ storecontract.SourceStore = (*EDA)(nil)
|
||||
_ storecontract.DispatchLedger = (*EDA)(nil)
|
||||
_ storecontract.BindingDispatcher = (*EDA)(nil)
|
||||
_ storecontract.PlaybookDispatcher = (*EDA)(nil)
|
||||
_ storecontract.HarnessSecretStore = (*EDA)(nil)
|
||||
)
|
||||
|
||||
// EDA is the PostgreSQL-backed EDA persistence.
|
||||
|
||||
@@ -14,8 +14,6 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/postgresdb"
|
||||
)
|
||||
|
||||
var _ storecontract.EventTypeStore = (*EDA)(nil)
|
||||
|
||||
func eventTypeValue(r postgresdb.EventType) (eventtype.EventType, error) {
|
||||
t := eventtype.EventType{
|
||||
ID: r.ID, Source: r.Source, Name: r.Name, WorkspaceID: org.WorkspaceID(r.WorkspaceID),
|
||||
|
||||
@@ -15,8 +15,6 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/postgresdb"
|
||||
)
|
||||
|
||||
var _ storecontract.HarnessSecretStore = (*EDA)(nil)
|
||||
|
||||
// harnessSecretPayload is the JSON shape sealed into harness_secrets.secret_enc:
|
||||
// the whole token set behind one envelope, never separate plaintext columns.
|
||||
type harnessSecretPayload struct {
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
-- +goose Up
|
||||
-- A workflow.handoff ends its run and starts a linked run of the next workflow
|
||||
-- on the same work item. Only the current run of an item is unique; a run
|
||||
-- that handed off points at its successor and leaves the key.
|
||||
ALTER TABLE tasks
|
||||
ADD COLUMN handoff_from_task_id bigint REFERENCES tasks (id) ON DELETE SET NULL,
|
||||
ADD COLUMN handoff_to_task_id bigint;
|
||||
ALTER TABLE tasks DROP CONSTRAINT tasks_org_identity_owner_repo_number_key;
|
||||
CREATE UNIQUE INDEX tasks_current_item_key ON tasks (org_id, identity, owner, repo, issue_number)
|
||||
WHERE handoff_to_task_id IS NULL;
|
||||
|
||||
-- +goose Down
|
||||
DELETE FROM tasks WHERE handoff_to_task_id IS NOT NULL;
|
||||
DROP INDEX tasks_current_item_key;
|
||||
ALTER TABLE tasks ADD CONSTRAINT tasks_org_identity_owner_repo_number_key
|
||||
UNIQUE (org_id, identity, owner, repo, issue_number);
|
||||
ALTER TABLE tasks DROP COLUMN handoff_to_task_id, DROP COLUMN handoff_from_task_id;
|
||||
@@ -24,7 +24,7 @@ func (q *Queries) CallStatusDetail(ctx context.Context, taskID int64) (string, e
|
||||
|
||||
const enqueueCallTask = `-- name: EnqueueCallTask :one
|
||||
WITH caller AS (
|
||||
SELECT t.id, t.owner, t.repo, t.issue_number, t.title, t.body, t.labels, t.status, t.workflow, t.branch, t.plan, t.notes, t.pr_number, t.tokens_used, t.iterations, t.attempt, t.park_reason, t.watch_comment_id, t.park_class, t.remediation_rounds, t.retry_count, t.source, t.identity, t.binding_id, t.binding_version, t.review_payload, t.workflow_definition_version, t.workflow_definition_digest, t.workflow_definition_yaml, t.created_at, t.updated_at, t.review_cursor, t.inputs, t.org_id, t.workspace_id, t.call_parent_task_id, t.call_depth, t.outputs, t.review_gate, t.rereview_rounds, t.retry_mode, t.resume_from, t.resume_results, t.pending_reviews, t.origin, t.call_key, t.binding_signature, t.binding_addr, t.park_blocker, t.outcome_posted_status, t.plan_document FROM tasks t WHERE t.id = $1 FOR UPDATE
|
||||
SELECT t.id, t.owner, t.repo, t.issue_number, t.title, t.body, t.labels, t.status, t.workflow, t.branch, t.plan, t.notes, t.pr_number, t.tokens_used, t.iterations, t.attempt, t.park_reason, t.watch_comment_id, t.park_class, t.remediation_rounds, t.retry_count, t.source, t.identity, t.binding_id, t.binding_version, t.review_payload, t.workflow_definition_version, t.workflow_definition_digest, t.workflow_definition_yaml, t.created_at, t.updated_at, t.review_cursor, t.inputs, t.org_id, t.workspace_id, t.call_parent_task_id, t.call_depth, t.outputs, t.review_gate, t.rereview_rounds, t.retry_mode, t.resume_from, t.resume_results, t.pending_reviews, t.origin, t.call_key, t.binding_signature, t.binding_addr, t.park_blocker, t.outcome_posted_status, t.plan_document, t.handoff_from_task_id, t.handoff_to_task_id FROM tasks t WHERE t.id = $1 FOR UPDATE
|
||||
), number AS (
|
||||
INSERT INTO chat_issue_numbers (owner, repo, last_number)
|
||||
SELECT caller.owner, caller.repo, $9::bigint + 1 FROM caller
|
||||
@@ -43,7 +43,7 @@ SELECT
|
||||
FROM caller, number
|
||||
WHERE caller.status = 'running' AND caller.call_depth + 1 <= $8::int
|
||||
ON CONFLICT (call_parent_task_id, call_key) WHERE call_key <> '' AND status NOT IN ('dead', 'closed_wont_do') DO UPDATE SET call_key = EXCLUDED.call_key
|
||||
RETURNING id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin, call_key, binding_signature, binding_addr, park_blocker, outcome_posted_status, plan_document
|
||||
RETURNING id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin, call_key, binding_signature, binding_addr, park_blocker, outcome_posted_status, plan_document, handoff_from_task_id, handoff_to_task_id
|
||||
`
|
||||
|
||||
type EnqueueCallTaskParams struct {
|
||||
@@ -137,6 +137,8 @@ func (q *Queries) EnqueueCallTask(ctx context.Context, arg EnqueueCallTaskParams
|
||||
&i.ParkBlocker,
|
||||
&i.OutcomePostedStatus,
|
||||
&i.PlanDocument,
|
||||
&i.HandoffFromTaskID,
|
||||
&i.HandoffToTaskID,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
@@ -584,6 +584,8 @@ type Task struct {
|
||||
ParkBlocker string
|
||||
OutcomePostedStatus string
|
||||
PlanDocument string
|
||||
HandoffFromTaskID pgtype.Int8
|
||||
HandoffToTaskID pgtype.Int8
|
||||
}
|
||||
|
||||
type ToolCall struct {
|
||||
|
||||
@@ -13,7 +13,7 @@ import (
|
||||
)
|
||||
|
||||
const activeTasksByOrigin = `-- name: ActiveTasksByOrigin :many
|
||||
SELECT id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin, call_key, binding_signature, binding_addr, park_blocker, outcome_posted_status, plan_document FROM tasks
|
||||
SELECT id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin, call_key, binding_signature, binding_addr, park_blocker, outcome_posted_status, plan_document, handoff_from_task_id, handoff_to_task_id FROM tasks
|
||||
WHERE origin = $1 AND origin <> '' AND status IN ('queued', 'running') AND ($2::text IS NULL OR org_id = $2)
|
||||
ORDER BY id
|
||||
`
|
||||
@@ -85,6 +85,8 @@ func (q *Queries) ActiveTasksByOrigin(ctx context.Context, arg ActiveTasksByOrig
|
||||
&i.ParkBlocker,
|
||||
&i.OutcomePostedStatus,
|
||||
&i.PlanDocument,
|
||||
&i.HandoffFromTaskID,
|
||||
&i.HandoffToTaskID,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -164,7 +166,7 @@ func (q *Queries) BeginRemediationTask(ctx context.Context, arg BeginRemediation
|
||||
const claimByIssue = `-- name: ClaimByIssue :one
|
||||
UPDATE tasks SET status = 'running', attempt = attempt + 1, outputs = '', updated_at = now()
|
||||
WHERE owner = $1 AND repo = $2 AND issue_number = $3 AND status = 'queued'
|
||||
RETURNING id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin, call_key, binding_signature, binding_addr, park_blocker, outcome_posted_status, plan_document
|
||||
RETURNING id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin, call_key, binding_signature, binding_addr, park_blocker, outcome_posted_status, plan_document, handoff_from_task_id, handoff_to_task_id
|
||||
`
|
||||
|
||||
type ClaimByIssueParams struct {
|
||||
@@ -230,6 +232,8 @@ func (q *Queries) ClaimByIssue(ctx context.Context, arg ClaimByIssueParams) (Tas
|
||||
&i.ParkBlocker,
|
||||
&i.OutcomePostedStatus,
|
||||
&i.PlanDocument,
|
||||
&i.HandoffFromTaskID,
|
||||
&i.HandoffToTaskID,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
@@ -244,7 +248,7 @@ WHERE id = (
|
||||
FOR UPDATE SKIP LOCKED
|
||||
LIMIT 1
|
||||
)
|
||||
RETURNING id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin, call_key, binding_signature, binding_addr, park_blocker, outcome_posted_status, plan_document
|
||||
RETURNING id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin, call_key, binding_signature, binding_addr, park_blocker, outcome_posted_status, plan_document, handoff_from_task_id, handoff_to_task_id
|
||||
`
|
||||
|
||||
// FOR UPDATE SKIP LOCKED replaces the SQLite single-writer assumption: two
|
||||
@@ -308,6 +312,8 @@ func (q *Queries) ClaimNextTask(ctx context.Context) (Task, error) {
|
||||
&i.ParkBlocker,
|
||||
&i.OutcomePostedStatus,
|
||||
&i.PlanDocument,
|
||||
&i.HandoffFromTaskID,
|
||||
&i.HandoffToTaskID,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
@@ -367,7 +373,7 @@ VALUES (
|
||||
),
|
||||
'default'
|
||||
)
|
||||
ON CONFLICT (org_id, identity, owner, repo, issue_number) DO NOTHING
|
||||
ON CONFLICT (org_id, identity, owner, repo, issue_number) WHERE handoff_to_task_id IS NULL DO NOTHING
|
||||
`
|
||||
|
||||
type EnqueueIssueParams struct {
|
||||
@@ -427,7 +433,7 @@ FROM number, (SELECT COALESCE(
|
||||
'org-sys'
|
||||
) AS id) AS owner_org
|
||||
WHERE $11::text IS NULL OR owner_org.id = $11
|
||||
RETURNING id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin, call_key, binding_signature, binding_addr, park_blocker, outcome_posted_status, plan_document
|
||||
RETURNING id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin, call_key, binding_signature, binding_addr, park_blocker, outcome_posted_status, plan_document, handoff_from_task_id, handoff_to_task_id
|
||||
`
|
||||
|
||||
type InsertChatTaskParams struct {
|
||||
@@ -525,6 +531,88 @@ func (q *Queries) InsertChatTask(ctx context.Context, arg InsertChatTaskParams)
|
||||
&i.ParkBlocker,
|
||||
&i.OutcomePostedStatus,
|
||||
&i.PlanDocument,
|
||||
&i.HandoffFromTaskID,
|
||||
&i.HandoffToTaskID,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const insertHandoffTask = `-- name: InsertHandoffTask :one
|
||||
INSERT INTO tasks (id, owner, repo, issue_number, title, body, labels, workflow, source, identity,
|
||||
org_id, workspace_id, inputs, plan, plan_document, binding_id, binding_version, binding_signature,
|
||||
binding_addr, origin, call_parent_task_id, call_depth, handoff_from_task_id)
|
||||
SELECT $1, t.owner, t.repo, t.issue_number, t.title, t.body, t.labels, $2, t.source, t.identity,
|
||||
t.org_id, t.workspace_id, t.inputs, t.plan, t.plan_document, t.binding_id, t.binding_version, t.binding_signature,
|
||||
t.binding_addr, t.origin, t.call_parent_task_id, t.call_depth, t.id
|
||||
FROM tasks t WHERE t.id = $3
|
||||
RETURNING id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin, call_key, binding_signature, binding_addr, park_blocker, outcome_posted_status, plan_document, handoff_from_task_id, handoff_to_task_id
|
||||
`
|
||||
|
||||
type InsertHandoffTaskParams struct {
|
||||
SuccessorID int64
|
||||
Workflow string
|
||||
ID int64
|
||||
}
|
||||
|
||||
// The successor run carries the work item and the decisions made on it; its
|
||||
// run state (attempts, branch, outputs, review state) starts fresh.
|
||||
func (q *Queries) InsertHandoffTask(ctx context.Context, arg InsertHandoffTaskParams) (Task, error) {
|
||||
row := q.db.QueryRow(ctx, insertHandoffTask, arg.SuccessorID, arg.Workflow, arg.ID)
|
||||
var i Task
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.Owner,
|
||||
&i.Repo,
|
||||
&i.IssueNumber,
|
||||
&i.Title,
|
||||
&i.Body,
|
||||
&i.Labels,
|
||||
&i.Status,
|
||||
&i.Workflow,
|
||||
&i.Branch,
|
||||
&i.Plan,
|
||||
&i.Notes,
|
||||
&i.PrNumber,
|
||||
&i.TokensUsed,
|
||||
&i.Iterations,
|
||||
&i.Attempt,
|
||||
&i.ParkReason,
|
||||
&i.WatchCommentID,
|
||||
&i.ParkClass,
|
||||
&i.RemediationRounds,
|
||||
&i.RetryCount,
|
||||
&i.Source,
|
||||
&i.Identity,
|
||||
&i.BindingID,
|
||||
&i.BindingVersion,
|
||||
&i.ReviewPayload,
|
||||
&i.WorkflowDefinitionVersion,
|
||||
&i.WorkflowDefinitionDigest,
|
||||
&i.WorkflowDefinitionYaml,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
&i.ReviewCursor,
|
||||
&i.Inputs,
|
||||
&i.OrgID,
|
||||
&i.WorkspaceID,
|
||||
&i.CallParentTaskID,
|
||||
&i.CallDepth,
|
||||
&i.Outputs,
|
||||
&i.ReviewGate,
|
||||
&i.RereviewRounds,
|
||||
&i.RetryMode,
|
||||
&i.ResumeFrom,
|
||||
&i.ResumeResults,
|
||||
&i.PendingReviews,
|
||||
&i.Origin,
|
||||
&i.CallKey,
|
||||
&i.BindingSignature,
|
||||
&i.BindingAddr,
|
||||
&i.ParkBlocker,
|
||||
&i.OutcomePostedStatus,
|
||||
&i.PlanDocument,
|
||||
&i.HandoffFromTaskID,
|
||||
&i.HandoffToTaskID,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
@@ -609,7 +697,8 @@ const listTaskSummaries = `-- name: ListTaskSummaries :many
|
||||
SELECT id, owner, repo, issue_number, title, status, workflow,
|
||||
pr_number, tokens_used, iterations, attempt, park_reason, retry_count,
|
||||
created_at, updated_at, plan, plan_document, source, identity, binding_id, binding_version,
|
||||
outputs, review_gate, rereview_rounds, org_id, park_class, park_blocker
|
||||
outputs, review_gate, rereview_rounds, org_id, park_class, park_blocker,
|
||||
handoff_from_task_id, handoff_to_task_id
|
||||
FROM tasks
|
||||
WHERE ($1::text IS NULL OR org_id = $1)
|
||||
AND (cardinality($2::text[]) = 0 OR status = ANY($2::text[]))
|
||||
@@ -630,33 +719,35 @@ type ListTaskSummariesParams struct {
|
||||
}
|
||||
|
||||
type ListTaskSummariesRow struct {
|
||||
ID int64
|
||||
Owner string
|
||||
Repo string
|
||||
IssueNumber int64
|
||||
Title string
|
||||
Status string
|
||||
Workflow string
|
||||
PrNumber int64
|
||||
TokensUsed int64
|
||||
Iterations int64
|
||||
Attempt int64
|
||||
ParkReason string
|
||||
RetryCount int64
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
Plan string
|
||||
PlanDocument string
|
||||
Source string
|
||||
Identity string
|
||||
BindingID string
|
||||
BindingVersion int64
|
||||
Outputs string
|
||||
ReviewGate string
|
||||
RereviewRounds int64
|
||||
OrgID string
|
||||
ParkClass string
|
||||
ParkBlocker string
|
||||
ID int64
|
||||
Owner string
|
||||
Repo string
|
||||
IssueNumber int64
|
||||
Title string
|
||||
Status string
|
||||
Workflow string
|
||||
PrNumber int64
|
||||
TokensUsed int64
|
||||
Iterations int64
|
||||
Attempt int64
|
||||
ParkReason string
|
||||
RetryCount int64
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
Plan string
|
||||
PlanDocument string
|
||||
Source string
|
||||
Identity string
|
||||
BindingID string
|
||||
BindingVersion int64
|
||||
Outputs string
|
||||
ReviewGate string
|
||||
RereviewRounds int64
|
||||
OrgID string
|
||||
ParkClass string
|
||||
ParkBlocker string
|
||||
HandoffFromTaskID pgtype.Int8
|
||||
HandoffToTaskID pgtype.Int8
|
||||
}
|
||||
|
||||
// The dashboard's list. This projection is deliberately narrow: Plan gates
|
||||
@@ -712,6 +803,8 @@ func (q *Queries) ListTaskSummaries(ctx context.Context, arg ListTaskSummariesPa
|
||||
&i.OrgID,
|
||||
&i.ParkClass,
|
||||
&i.ParkBlocker,
|
||||
&i.HandoffFromTaskID,
|
||||
&i.HandoffToTaskID,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -763,6 +856,25 @@ func (q *Queries) LockTaskStatus(ctx context.Context, id int64) (string, error)
|
||||
return status, err
|
||||
}
|
||||
|
||||
const markHandedOff = `-- name: MarkHandedOff :execrows
|
||||
UPDATE tasks SET handoff_to_task_id = $1, updated_at = now()
|
||||
WHERE id = $2 AND handoff_to_task_id IS NULL
|
||||
`
|
||||
|
||||
type MarkHandedOffParams struct {
|
||||
SuccessorID pgtype.Int8
|
||||
ID int64
|
||||
}
|
||||
|
||||
// The run leaves the item's unique key before its successor takes it.
|
||||
func (q *Queries) MarkHandedOff(ctx context.Context, arg MarkHandedOffParams) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, markHandedOff, arg.SuccessorID, arg.ID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const markOutcomePosted = `-- name: MarkOutcomePosted :exec
|
||||
UPDATE tasks SET outcome_posted_status = COALESCE(NULLIF($1::text, ''), status) WHERE id = $2
|
||||
`
|
||||
@@ -780,6 +892,17 @@ func (q *Queries) MarkOutcomePosted(ctx context.Context, arg MarkOutcomePostedPa
|
||||
return err
|
||||
}
|
||||
|
||||
const nextTaskID = `-- name: NextTaskID :one
|
||||
SELECT nextval(pg_get_serial_sequence('tasks', 'id'))::bigint
|
||||
`
|
||||
|
||||
func (q *Queries) NextTaskID(ctx context.Context) (int64, error) {
|
||||
row := q.db.QueryRow(ctx, nextTaskID)
|
||||
var column_1 int64
|
||||
err := row.Scan(&column_1)
|
||||
return column_1, err
|
||||
}
|
||||
|
||||
const parkTask = `-- name: ParkTask :execrows
|
||||
UPDATE tasks
|
||||
SET status = 'parked', park_reason = $2, park_class = $3, park_blocker = $5, updated_at = now()
|
||||
@@ -1014,7 +1137,7 @@ func (q *Queries) StampTaskBinding(ctx context.Context, arg StampTaskBindingPara
|
||||
}
|
||||
|
||||
const taskByID = `-- name: TaskByID :one
|
||||
SELECT id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin, call_key, binding_signature, binding_addr, park_blocker, outcome_posted_status, plan_document FROM tasks WHERE id = $1 AND ($2::text IS NULL OR org_id = $2)
|
||||
SELECT id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin, call_key, binding_signature, binding_addr, park_blocker, outcome_posted_status, plan_document, handoff_from_task_id, handoff_to_task_id FROM tasks WHERE id = $1 AND ($2::text IS NULL OR org_id = $2)
|
||||
`
|
||||
|
||||
type TaskByIDParams struct {
|
||||
@@ -1077,12 +1200,14 @@ func (q *Queries) TaskByID(ctx context.Context, arg TaskByIDParams) (Task, error
|
||||
&i.ParkBlocker,
|
||||
&i.OutcomePostedStatus,
|
||||
&i.PlanDocument,
|
||||
&i.HandoffFromTaskID,
|
||||
&i.HandoffToTaskID,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const taskByIssue = `-- name: TaskByIssue :one
|
||||
SELECT id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin, call_key, binding_signature, binding_addr, park_blocker, outcome_posted_status, plan_document FROM tasks WHERE owner = $1 AND repo = $2 AND issue_number = $3
|
||||
SELECT id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin, call_key, binding_signature, binding_addr, park_blocker, outcome_posted_status, plan_document, handoff_from_task_id, handoff_to_task_id FROM tasks WHERE owner = $1 AND repo = $2 AND issue_number = $3 AND handoff_to_task_id IS NULL
|
||||
AND ($4::text IS NULL OR org_id = $4)
|
||||
`
|
||||
|
||||
@@ -1153,12 +1278,14 @@ func (q *Queries) TaskByIssue(ctx context.Context, arg TaskByIssueParams) (Task,
|
||||
&i.ParkBlocker,
|
||||
&i.OutcomePostedStatus,
|
||||
&i.PlanDocument,
|
||||
&i.HandoffFromTaskID,
|
||||
&i.HandoffToTaskID,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const taskByPR = `-- name: TaskByPR :one
|
||||
SELECT id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin, call_key, binding_signature, binding_addr, park_blocker, outcome_posted_status, plan_document FROM tasks WHERE owner = $1 AND repo = $2 AND pr_number = $3 AND status = $4
|
||||
SELECT id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin, call_key, binding_signature, binding_addr, park_blocker, outcome_posted_status, plan_document, handoff_from_task_id, handoff_to_task_id FROM tasks WHERE owner = $1 AND repo = $2 AND pr_number = $3 AND status = $4
|
||||
AND ($5::text IS NULL OR org_id = $5)
|
||||
`
|
||||
|
||||
@@ -1234,6 +1361,8 @@ func (q *Queries) TaskByPR(ctx context.Context, arg TaskByPRParams) (Task, error
|
||||
&i.ParkBlocker,
|
||||
&i.OutcomePostedStatus,
|
||||
&i.PlanDocument,
|
||||
&i.HandoffFromTaskID,
|
||||
&i.HandoffToTaskID,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
@@ -1273,9 +1402,10 @@ func (q *Queries) TransitionTask(ctx context.Context, arg TransitionTaskParams)
|
||||
}
|
||||
|
||||
const unpostedOutcomes = `-- name: UnpostedOutcomes :many
|
||||
SELECT id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin, call_key, binding_signature, binding_addr, park_blocker, outcome_posted_status, plan_document FROM tasks
|
||||
SELECT id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin, call_key, binding_signature, binding_addr, park_blocker, outcome_posted_status, plan_document, handoff_from_task_id, handoff_to_task_id FROM tasks
|
||||
WHERE origin <> '' AND outcome_posted_status <> status
|
||||
AND status IN ('merged', 'rejected', 'dead', 'closed_wont_do', 'completed', 'waiting_approval', 'pr_open')
|
||||
AND handoff_to_task_id IS NULL
|
||||
AND ($1::text IS NULL OR org_id = $1)
|
||||
ORDER BY id
|
||||
LIMIT 50
|
||||
@@ -1344,6 +1474,8 @@ func (q *Queries) UnpostedOutcomes(ctx context.Context, scopeOrg pgtype.Text) ([
|
||||
&i.ParkBlocker,
|
||||
&i.OutcomePostedStatus,
|
||||
&i.PlanDocument,
|
||||
&i.HandoffFromTaskID,
|
||||
&i.HandoffToTaskID,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -20,7 +20,7 @@ RETURNING *;
|
||||
SELECT * FROM tasks WHERE id = sqlc.arg(id) AND (sqlc.narg(scope_org)::text IS NULL OR org_id = sqlc.narg(scope_org));
|
||||
|
||||
-- name: TaskByIssue :one
|
||||
SELECT * FROM tasks WHERE owner = sqlc.arg(owner) AND repo = sqlc.arg(repo) AND issue_number = sqlc.arg(issue_number)
|
||||
SELECT * FROM tasks WHERE owner = sqlc.arg(owner) AND repo = sqlc.arg(repo) AND issue_number = sqlc.arg(issue_number) AND handoff_to_task_id IS NULL
|
||||
AND (sqlc.narg(scope_org)::text IS NULL OR org_id = sqlc.narg(scope_org));
|
||||
|
||||
-- name: TaskByPR :one
|
||||
@@ -43,7 +43,8 @@ SELECT * FROM tasks WHERE owner = sqlc.arg(owner) AND repo = sqlc.arg(repo) AND
|
||||
SELECT id, owner, repo, issue_number, title, status, workflow,
|
||||
pr_number, tokens_used, iterations, attempt, park_reason, retry_count,
|
||||
created_at, updated_at, plan, plan_document, source, identity, binding_id, binding_version,
|
||||
outputs, review_gate, rereview_rounds, org_id, park_class, park_blocker
|
||||
outputs, review_gate, rereview_rounds, org_id, park_class, park_blocker,
|
||||
handoff_from_task_id, handoff_to_task_id
|
||||
FROM tasks
|
||||
WHERE (sqlc.narg(scope_org)::text IS NULL OR org_id = sqlc.narg(scope_org))
|
||||
AND (cardinality(@statuses::text[]) = 0 OR status = ANY(@statuses::text[]))
|
||||
@@ -109,6 +110,7 @@ ORDER BY id;
|
||||
SELECT * FROM tasks
|
||||
WHERE origin <> '' AND outcome_posted_status <> status
|
||||
AND status IN ('merged', 'rejected', 'dead', 'closed_wont_do', 'completed', 'waiting_approval', 'pr_open')
|
||||
AND handoff_to_task_id IS NULL
|
||||
AND (sqlc.narg(scope_org)::text IS NULL OR org_id = sqlc.narg(scope_org))
|
||||
ORDER BY id
|
||||
LIMIT 50;
|
||||
@@ -199,7 +201,7 @@ VALUES (
|
||||
),
|
||||
'default'
|
||||
)
|
||||
ON CONFLICT (org_id, identity, owner, repo, issue_number) DO NOTHING;
|
||||
ON CONFLICT (org_id, identity, owner, repo, issue_number) WHERE handoff_to_task_id IS NULL DO NOTHING;
|
||||
|
||||
-- name: ClaimByIssue :one
|
||||
-- The claim starts the attempt's output set empty, as ClaimNextTask does:
|
||||
@@ -291,3 +293,23 @@ DELETE FROM tasks WHERE id = $1 AND status = $2;
|
||||
-- name: ListOpenPRs :many
|
||||
SELECT id, owner, repo, issue_number, pr_number, status, source, identity, attempt, review_cursor, watch_comment_id, outputs
|
||||
FROM tasks WHERE status = 'pr_open' AND (sqlc.narg(scope_org)::text IS NULL OR org_id = sqlc.narg(scope_org));
|
||||
|
||||
-- name: NextTaskID :one
|
||||
SELECT nextval(pg_get_serial_sequence('tasks', 'id'))::bigint;
|
||||
|
||||
-- name: MarkHandedOff :execrows
|
||||
-- The run leaves the item's unique key before its successor takes it.
|
||||
UPDATE tasks SET handoff_to_task_id = sqlc.arg(successor_id), updated_at = now()
|
||||
WHERE id = sqlc.arg(id) AND handoff_to_task_id IS NULL;
|
||||
|
||||
-- name: InsertHandoffTask :one
|
||||
-- The successor run carries the work item and the decisions made on it; its
|
||||
-- run state (attempts, branch, outputs, review state) starts fresh.
|
||||
INSERT INTO tasks (id, owner, repo, issue_number, title, body, labels, workflow, source, identity,
|
||||
org_id, workspace_id, inputs, plan, plan_document, binding_id, binding_version, binding_signature,
|
||||
binding_addr, origin, call_parent_task_id, call_depth, handoff_from_task_id)
|
||||
SELECT sqlc.arg(successor_id), t.owner, t.repo, t.issue_number, t.title, t.body, t.labels, sqlc.arg(workflow), t.source, t.identity,
|
||||
t.org_id, t.workspace_id, t.inputs, t.plan, t.plan_document, t.binding_id, t.binding_version, t.binding_signature,
|
||||
t.binding_addr, t.origin, t.call_parent_task_id, t.call_depth, t.id
|
||||
FROM tasks t WHERE t.id = sqlc.arg(id)
|
||||
RETURNING *;
|
||||
@@ -11,8 +11,6 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/postgresdb"
|
||||
)
|
||||
|
||||
var _ storecontract.RunCredentialStore = (*Store)(nil)
|
||||
|
||||
func (s *Store) PutRunCredential(ctx context.Context, digest [32]byte, taskID int64, expires time.Time) error {
|
||||
return s.queries().InsertRunCredential(ctx, postgresdb.InsertRunCredentialParams{Digest: digest[:], TaskID: taskID, ExpiresAt: expires})
|
||||
}
|
||||
|
||||
@@ -13,8 +13,6 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/postgresdb"
|
||||
)
|
||||
|
||||
var _ storecontract.SourceStore = (*EDA)(nil)
|
||||
|
||||
// InsertSource stores a new source in one of the acting org's workspaces,
|
||||
// its default one when src names none; a workspace the org does not have is
|
||||
// ErrInvalidWorkspace. The path is the primary key, so a taken path is
|
||||
|
||||
@@ -124,6 +124,8 @@ func taskFromRow(t postgresdb.Task) *workflow.Task {
|
||||
ParkBlocker: t.ParkBlocker,
|
||||
RemediationRounds: int(t.RemediationRounds),
|
||||
CallParentTaskID: t.CallParentTaskID,
|
||||
HandoffFromTaskID: t.HandoffFromTaskID.Int64,
|
||||
HandoffToTaskID: t.HandoffToTaskID.Int64,
|
||||
CallDepth: int(t.CallDepth),
|
||||
Origin: t.Origin,
|
||||
CreatedAt: t.CreatedAt,
|
||||
@@ -134,9 +136,20 @@ func taskFromRow(t postgresdb.Task) *workflow.Task {
|
||||
// Compile-time checks: *Store satisfies every surface the SQLite store did.
|
||||
var (
|
||||
_ storecontract.TaskStore = (*Store)(nil)
|
||||
_ storecontract.TaskLifecycle = (*Store)(nil)
|
||||
_ storecontract.TaskParker = (*Store)(nil)
|
||||
_ storecontract.TaskQueries = (*Store)(nil)
|
||||
_ storecontract.TaskEvents = (*Store)(nil)
|
||||
_ storecontract.TaskArchiver = (*Store)(nil)
|
||||
_ storecontract.TaskRetryer = (*Store)(nil)
|
||||
_ storecontract.ReviewGateResponder = (*Store)(nil)
|
||||
_ storecontract.RemediationStarter = (*Store)(nil)
|
||||
_ storecontract.OutcomePoster = (*Store)(nil)
|
||||
_ storecontract.StepRecorder = (*Store)(nil)
|
||||
_ storecontract.StepReader = (*Store)(nil)
|
||||
_ storecontract.ExecutionCanceller = (*Store)(nil)
|
||||
_ storecontract.BindingTaskCreator = (*Store)(nil)
|
||||
_ storecontract.RunCredentialStore = (*Store)(nil)
|
||||
_ storecontract.ConfigSnapshotStore = (*Store)(nil)
|
||||
_ storecontract.ChannelStatusStore = (*Store)(nil)
|
||||
_ storecontract.ApplyStatusStore = (*Store)(nil)
|
||||
@@ -779,6 +792,7 @@ func (s *Store) TasksPage(ctx context.Context, page storecontract.TaskPage) ([]w
|
||||
Outputs: outputs,
|
||||
ReviewGate: r.ReviewGate, RereviewRounds: int(r.RereviewRounds),
|
||||
Org: org.OrgID(r.OrgID), ParkClass: r.ParkClass, ParkBlocker: r.ParkBlocker,
|
||||
HandoffFromTaskID: r.HandoffFromTaskID.Int64, HandoffToTaskID: r.HandoffToTaskID.Int64,
|
||||
})
|
||||
}
|
||||
return tasks, nil
|
||||
@@ -875,6 +889,58 @@ func (s *Store) StartCall(ctx context.Context, callerTaskID int64, callKey, wf s
|
||||
return taskFromRow(callee), nil
|
||||
}
|
||||
|
||||
// Handoff completes the running task fromTaskID and starts its linked
|
||||
// successor on the same work item under wf, in one transaction: the item is
|
||||
// never without a current run, and never has two.
|
||||
func (s *Store) Handoff(ctx context.Context, fromTaskID int64, wf, detail string) (*workflow.Task, error) {
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
q := postgresdb.New(tx)
|
||||
from, to := workflow.StatusRunning, workflow.StatusCompleted
|
||||
if err := guardTransition(ctx, q, fromTaskID, from, to); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
n, err := q.TransitionTask(ctx, postgresdb.TransitionTaskParams{
|
||||
ID: fromTaskID, Status: to, ParkClass: taskstate.ParkNeedsDecision, Status_2: from,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if n == 0 {
|
||||
return nil, storecontract.ErrStaleTransition
|
||||
}
|
||||
if err := recordTransition(ctx, q, postgresdb.InsertTransitionParams{
|
||||
TaskID: fromTaskID, FromStatus: from, ToStatus: to, Detail: clip(detail, 4000),
|
||||
}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
successor, err := q.NextTaskID(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if n, err := q.MarkHandedOff(ctx, postgresdb.MarkHandedOffParams{ID: fromTaskID, SuccessorID: pgtype.Int8{Int64: successor, Valid: true}}); err != nil {
|
||||
return nil, err
|
||||
} else if n == 0 {
|
||||
return nil, fmt.Errorf("store: task %d already handed off: %w", fromTaskID, storecontract.ErrStaleTransition)
|
||||
}
|
||||
row, err := q.InsertHandoffTask(ctx, postgresdb.InsertHandoffTaskParams{ID: fromTaskID, SuccessorID: successor, Workflow: wf})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := recordTransition(ctx, q, postgresdb.InsertTransitionParams{
|
||||
TaskID: row.ID, FromStatus: "", ToStatus: workflow.StatusQueued, Detail: fmt.Sprintf("handed off from task %d", fromTaskID),
|
||||
}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return taskFromRow(row), nil
|
||||
}
|
||||
|
||||
// callerIdentity is the identity the caller's pinned workflow declares, the
|
||||
// one its callees are started by. The pin does not change while the caller's
|
||||
// call step runs.
|
||||
|
||||
@@ -111,6 +111,18 @@ var (
|
||||
_ storecontract.PresenceStore = (*Client)(nil)
|
||||
_ storecontract.CaptureRefusalStore = (*Client)(nil)
|
||||
_ storecontract.ExecutionCanceller = (*Client)(nil)
|
||||
_ storecontract.TaskLifecycle = (*Client)(nil)
|
||||
_ storecontract.TaskParker = (*Client)(nil)
|
||||
_ storecontract.TaskQueries = (*Client)(nil)
|
||||
_ storecontract.TaskEvents = (*Client)(nil)
|
||||
_ storecontract.TaskArchiver = (*Client)(nil)
|
||||
_ storecontract.TaskRetryer = (*Client)(nil)
|
||||
_ storecontract.ReviewGateResponder = (*Client)(nil)
|
||||
_ storecontract.RemediationStarter = (*Client)(nil)
|
||||
_ storecontract.OutcomePoster = (*Client)(nil)
|
||||
_ storecontract.StepReader = (*Client)(nil)
|
||||
_ storecontract.DispatchLedger = (*Client)(nil)
|
||||
_ storecontract.EventTypeStore = (*Client)(nil)
|
||||
_ identity.Repository = (*Client)(nil)
|
||||
_ storepkg.Installations = (*Client)(nil)
|
||||
_ identity.PersonalTokens = (*Client)(nil)
|
||||
|
||||
@@ -149,6 +149,13 @@ var taskScopedTargets = map[string]func(any) int64{
|
||||
}
|
||||
return r.CallerTaskId
|
||||
},
|
||||
pb.TaskService_HandoffTask_FullMethodName: func(req any) int64 {
|
||||
r, ok := req.(*pb.HandoffTaskRequest)
|
||||
if !ok {
|
||||
return 0
|
||||
}
|
||||
return r.TaskId
|
||||
},
|
||||
pb.TaskService_WorkflowCallStatus_FullMethodName: func(req any) int64 {
|
||||
r, ok := req.(*pb.WorkflowCallStatusRequest)
|
||||
if !ok {
|
||||
|
||||
@@ -267,6 +267,20 @@ func (s *taskServer) EnqueueCallTask(ctx context.Context, r *pb.EnqueueCallTaskR
|
||||
return &pb.EnqueueCallTaskResponse{Task: taskProto(t), Accepted: true}, nil
|
||||
}
|
||||
|
||||
func (s *taskServer) HandoffTask(ctx context.Context, r *pb.HandoffTaskRequest) (*pb.HandoffTaskResponse, error) {
|
||||
if s.deps.WorkflowCalls == nil {
|
||||
return nil, errWorkflowCallerUnavailable
|
||||
}
|
||||
if r.TaskId <= 0 || r.Workflow == "" {
|
||||
return nil, status.Error(codes.InvalidArgument, "task id and workflow are required")
|
||||
}
|
||||
t, err := s.deps.WorkflowCalls.Handoff(ctx, r.TaskId, r.Workflow, r.Detail)
|
||||
if err != nil {
|
||||
return nil, s.logErr("HandoffTask", err)
|
||||
}
|
||||
return &pb.HandoffTaskResponse{Task: taskProto(t)}, nil
|
||||
}
|
||||
|
||||
func (s *taskServer) WorkflowCallStatus(ctx context.Context, r *pb.WorkflowCallStatusRequest) (*pb.WorkflowCallStatusResponse, error) {
|
||||
if s.deps.WorkflowCalls == nil {
|
||||
return nil, errWorkflowCallerUnavailable
|
||||
@@ -485,6 +499,14 @@ func (c *Client) StartCall(ctx context.Context, callerTaskID int64, callKey, wf
|
||||
return taskValue(r.Task), nil
|
||||
}
|
||||
|
||||
func (c *Client) Handoff(ctx context.Context, fromTaskID int64, wf, detail string) (*task.Task, error) {
|
||||
r, err := c.task.HandoffTask(ctx, &pb.HandoffTaskRequest{TaskId: fromTaskID, Workflow: wf, Detail: detail})
|
||||
if err != nil {
|
||||
return nil, unmapError(err)
|
||||
}
|
||||
return taskValue(r.Task), nil
|
||||
}
|
||||
|
||||
func (c *Client) CallStatus(ctx context.Context, callerTaskID, callTaskID int64) (string, string, map[string]any, error) {
|
||||
r, err := c.task.WorkflowCallStatus(ctx, &pb.WorkflowCallStatusRequest{CallerTaskId: callerTaskID, CallTaskId: callTaskID})
|
||||
if err != nil {
|
||||
|
||||
@@ -85,6 +85,8 @@ func taskProto(t *task.Task) *pb.Task { // mirror-image field-by-field proto<->d
|
||||
Org: string(t.Org),
|
||||
Workspace: string(t.Workspace),
|
||||
CallParentTaskId: t.CallParentTaskID,
|
||||
HandoffFromTaskId: t.HandoffFromTaskID,
|
||||
HandoffToTaskId: t.HandoffToTaskID,
|
||||
CallDepth: int32(t.CallDepth),
|
||||
Origin: t.Origin,
|
||||
BindingSignature: t.BindingSignature,
|
||||
@@ -122,6 +124,8 @@ func taskValue(t *pb.Task) *task.Task { // see taskProto above
|
||||
Org: org.OrgID(t.Org),
|
||||
Workspace: org.WorkspaceID(t.Workspace),
|
||||
CallParentTaskID: t.CallParentTaskId,
|
||||
HandoffFromTaskID: t.HandoffFromTaskId,
|
||||
HandoffToTaskID: t.HandoffToTaskId,
|
||||
CallDepth: int(t.CallDepth),
|
||||
Origin: t.Origin,
|
||||
BindingSignature: t.BindingSignature,
|
||||
|
||||
@@ -13,8 +13,8 @@ const defaultDenialsListLimit = 100
|
||||
// first. The route's read_audit grant limits it to the org's admins and
|
||||
// owners, and the store scopes the list by the credential's org, so no
|
||||
// request field chooses the org an operator reads.
|
||||
func (s *Server) handleListDenials(w http.ResponseWriter, r *http.Request) {
|
||||
if s.DenialLister == nil {
|
||||
func (a *accessAPI) handleListDenials(w http.ResponseWriter, r *http.Request) {
|
||||
if a.denials == nil {
|
||||
http.Error(w, "denial records unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
@@ -22,7 +22,7 @@ func (s *Server) handleListDenials(w http.ResponseWriter, r *http.Request) {
|
||||
if err != nil || limit <= 0 || limit > 1000 {
|
||||
limit = defaultDenialsListLimit
|
||||
}
|
||||
denials, err := s.DenialLister.ListDenials(r.Context(), policyOrg(r), int(limit))
|
||||
denials, err := a.denials.ListDenials(r.Context(), policyOrg(r), int(limit))
|
||||
if err != nil {
|
||||
writeControlPlaneError(w, err)
|
||||
return
|
||||
@@ -95,7 +95,7 @@ func TestHandleListDenialsScopesToCallersOrg(t *testing.T) {
|
||||
ctx := org.WithOrg(access.WithPrincipal(t.Context(), principal), tt.caller)
|
||||
req := httptest.NewRequestWithContext(ctx, http.MethodGet, "/api/access/denials"+tt.query, nil)
|
||||
rec := httptest.NewRecorder()
|
||||
srv.handleListDenials(rec, req)
|
||||
newAccessAPI(srv).handleListDenials(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200 body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
@@ -129,7 +129,7 @@ func TestHandleListDenialsUnwired(t *testing.T) {
|
||||
srv := &Server{}
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/access/denials", nil)
|
||||
rec := httptest.NewRecorder()
|
||||
srv.handleListDenials(rec, req)
|
||||
newAccessAPI(srv).handleListDenials(rec, req)
|
||||
if rec.Code != http.StatusServiceUnavailable {
|
||||
t.Fatalf("status = %d, want 503", rec.Code)
|
||||
}
|
||||
@@ -9,6 +9,24 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/domain/org"
|
||||
)
|
||||
|
||||
// accessAPI owns the /api/access routes: the stored policy chain and the
|
||||
// recorded denials. Either store may be nil; its routes then answer 503.
|
||||
type accessAPI struct {
|
||||
policies access.PolicyStore
|
||||
denials access.DenialStore
|
||||
}
|
||||
|
||||
func newAccessAPI(s *Server) *accessAPI {
|
||||
return &accessAPI{policies: s.Policies, denials: s.DenialLister}
|
||||
}
|
||||
|
||||
func (a *accessAPI) register(mux *http.ServeMux) {
|
||||
mux.HandleFunc("GET /api/access/policies", a.handleListPolicies)
|
||||
mux.HandleFunc("PUT /api/access/policies", a.handlePutPolicy)
|
||||
mux.HandleFunc("DELETE /api/access/policies", a.handleDeletePolicy)
|
||||
mux.HandleFunc("GET /api/access/denials", a.handleListDenials)
|
||||
}
|
||||
|
||||
// policyOrg is the org a policy request acts in: the caller's.
|
||||
func policyOrg(r *http.Request) org.OrgID {
|
||||
if principal, ok := access.PrincipalFromContext(r.Context()); ok {
|
||||
@@ -19,12 +37,12 @@ func policyOrg(r *http.Request) org.OrgID {
|
||||
|
||||
// handleListPolicies lists the caller's org policies, and the instance
|
||||
// policies when the caller is the instance owner.
|
||||
func (s *Server) handleListPolicies(w http.ResponseWriter, r *http.Request) {
|
||||
if s.Policies == nil {
|
||||
func (a *accessAPI) handleListPolicies(w http.ResponseWriter, r *http.Request) {
|
||||
if a.policies == nil {
|
||||
http.Error(w, "policies unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
policies, err := s.Policies.ListPolicies(r.Context())
|
||||
policies, err := a.policies.ListPolicies(r.Context())
|
||||
if err != nil {
|
||||
writeControlPlaneError(w, err)
|
||||
return
|
||||
@@ -39,12 +57,12 @@ func (s *Server) handleListPolicies(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, map[string]any{"policies": out, "shipped": shippedPolicyIDs()})
|
||||
}
|
||||
|
||||
func (s *Server) handlePutPolicy(w http.ResponseWriter, r *http.Request) {
|
||||
p, ok := s.decodePolicy(w, r)
|
||||
func (a *accessAPI) handlePutPolicy(w http.ResponseWriter, r *http.Request) {
|
||||
p, ok := a.decodePolicy(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
version, err := s.Policies.PutPolicy(r.Context(), p)
|
||||
version, err := a.policies.PutPolicy(r.Context(), p)
|
||||
if err != nil {
|
||||
writePolicyError(w, err)
|
||||
return
|
||||
@@ -52,12 +70,12 @@ func (s *Server) handlePutPolicy(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, map[string]int64{"version": version})
|
||||
}
|
||||
|
||||
func (s *Server) handleDeletePolicy(w http.ResponseWriter, r *http.Request) {
|
||||
p, ok := s.decodePolicy(w, r)
|
||||
func (a *accessAPI) handleDeletePolicy(w http.ResponseWriter, r *http.Request) {
|
||||
p, ok := a.decodePolicy(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if err := s.Policies.DeletePolicy(r.Context(), p); err != nil {
|
||||
if err := a.policies.DeletePolicy(r.Context(), p); err != nil {
|
||||
writePolicyError(w, err)
|
||||
return
|
||||
}
|
||||
@@ -66,8 +84,8 @@ func (s *Server) handleDeletePolicy(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
// decodePolicy reads a policy and pins it to the caller's org: no request
|
||||
// field chooses the org, and instance policies are not edited here.
|
||||
func (s *Server) decodePolicy(w http.ResponseWriter, r *http.Request) (access.Policy, bool) {
|
||||
if s.Policies == nil {
|
||||
func (a *accessAPI) decodePolicy(w http.ResponseWriter, r *http.Request) (access.Policy, bool) {
|
||||
if a.policies == nil {
|
||||
http.Error(w, "policies unavailable", http.StatusServiceUnavailable)
|
||||
return access.Policy{}, false
|
||||
}
|
||||
File renamed without changes.
@@ -417,3 +417,16 @@ func (s *Server) authenticateBrowser(ctx context.Context, credential string) (id
|
||||
}
|
||||
return verify(ctx, credential)
|
||||
}
|
||||
|
||||
func (s *Server) memberIssuer(r *http.Request) string {
|
||||
if store, ok := s.authenticationSettings(); ok {
|
||||
value, err := store.AuthenticationSettings(r.Context())
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
if value.PublicURL != "" {
|
||||
return value.OIDCIssuer
|
||||
}
|
||||
}
|
||||
return s.Issuer
|
||||
}
|
||||
@@ -245,7 +245,7 @@ func TestIdentityTokenCreate(t *testing.T) {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.SetPathValue("id", tt.id)
|
||||
rec := httptest.NewRecorder()
|
||||
srv.handleIdentityTokenCreate(rec, req)
|
||||
newIdentitiesAPI(srv).handleIdentityTokenCreate(rec, req)
|
||||
if rec.Code != tt.want {
|
||||
t.Fatalf("status=%d want=%d body=%s", rec.Code, tt.want, rec.Body.String())
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ package webui
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -72,10 +73,23 @@ func viewOfAlert(a alert.Alert) alertView {
|
||||
return view
|
||||
}
|
||||
|
||||
// alertsAPI owns the /api/alerts routes. A nil source answers 503.
|
||||
type alertsAPI struct {
|
||||
alerts AlertSource
|
||||
log *slog.Logger
|
||||
}
|
||||
|
||||
func newAlertsAPI(s *Server) *alertsAPI { return &alertsAPI{alerts: s.Alerts, log: s.Log} }
|
||||
|
||||
func (a *alertsAPI) register(mux *http.ServeMux) {
|
||||
mux.HandleFunc("GET /api/alerts", a.handleAlerts)
|
||||
mux.HandleFunc("POST /api/alerts/{id}/dismiss", a.handleAlertDismiss)
|
||||
}
|
||||
|
||||
// handleAlerts lists the caller's org's alerts: open ones unless ?state names
|
||||
// others (comma separated), most severe first.
|
||||
func (s *Server) handleAlerts(w http.ResponseWriter, r *http.Request) {
|
||||
if s.Alerts == nil {
|
||||
func (a *alertsAPI) handleAlerts(w http.ResponseWriter, r *http.Request) {
|
||||
if a.alerts == nil {
|
||||
http.Error(w, "alerts unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
@@ -85,9 +99,9 @@ func (s *Server) handleAlerts(w http.ResponseWriter, r *http.Request) {
|
||||
filter.States = append(filter.States, alert.State(strings.TrimSpace(state)))
|
||||
}
|
||||
}
|
||||
alerts, err := s.Alerts.ListAlerts(r.Context(), policyOrg(r), filter)
|
||||
alerts, err := a.alerts.ListAlerts(r.Context(), policyOrg(r), filter)
|
||||
if err != nil {
|
||||
s.Log.ErrorContext(r.Context(), "list alerts", "err", err)
|
||||
a.log.ErrorContext(r.Context(), "list alerts", "err", err)
|
||||
http.Error(w, "list alerts failed", http.StatusBadGateway)
|
||||
return
|
||||
}
|
||||
@@ -99,8 +113,8 @@ func (s *Server) handleAlerts(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
// handleAlertDismiss dismisses one open alert of the caller's org.
|
||||
func (s *Server) handleAlertDismiss(w http.ResponseWriter, r *http.Request) {
|
||||
if s.Alerts == nil {
|
||||
func (a *alertsAPI) handleAlertDismiss(w http.ResponseWriter, r *http.Request) {
|
||||
if a.alerts == nil {
|
||||
http.Error(w, "alerts unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
@@ -109,12 +123,12 @@ func (s *Server) handleAlertDismiss(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, "invalid alert id", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
err = s.Alerts.DismissAlert(r.Context(), policyOrg(r), id, access.ActorFromContext(r.Context()))
|
||||
err = a.alerts.DismissAlert(r.Context(), policyOrg(r), id, access.ActorFromContext(r.Context()))
|
||||
switch {
|
||||
case errors.Is(err, alert.ErrNotFound):
|
||||
http.Error(w, "alert not found", http.StatusNotFound)
|
||||
case err != nil:
|
||||
s.Log.ErrorContext(r.Context(), "dismiss alert", "err", err)
|
||||
a.log.ErrorContext(r.Context(), "dismiss alert", "err", err)
|
||||
http.Error(w, "dismiss alert failed", http.StatusBadGateway)
|
||||
default:
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
@@ -1,159 +1,14 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/binding"
|
||||
"github.com/samcharles93/archie-core/internal/domain/org"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
|
||||
)
|
||||
|
||||
// bindingRequest is the wire shape POST /api/bindings and
|
||||
// PATCH /api/bindings/{id} both accept. ID/Version/Status/CreatedAt/UpdatedAt
|
||||
// are server-assigned (or server-driven), never taken from the request body.
|
||||
type bindingRequest struct {
|
||||
Name string `json:"name"`
|
||||
Matcher binding.Matcher `json:"matcher"`
|
||||
MappingID string `json:"mapping_id"`
|
||||
Filter string `json:"filter"`
|
||||
Workflow string `json:"workflow"`
|
||||
// Owner and Repo optionally pin the binding to one configured repo,
|
||||
// for multi-repo deployments. Both empty is valid (falls back to the
|
||||
// daemon's single-configured-repo behaviour); binding.Validate
|
||||
// rejects setting only one.
|
||||
Owner string `json:"owner"`
|
||||
Repo string `json:"repo"`
|
||||
// RepoParam takes the repository from a mapped parameter instead.
|
||||
RepoParam string `json:"repo_param"`
|
||||
Inputs map[string]binding.InputSource `json:"inputs"`
|
||||
}
|
||||
|
||||
// bindingView is a listed binding with its source's signing state, so the
|
||||
// list can flag a binding that dispatches unsigned events.
|
||||
type bindingView struct {
|
||||
binding.Binding
|
||||
Unsigned bool `json:"unsigned"`
|
||||
// WorkflowDisabled marks a binding whose org has disabled the workflow it
|
||||
// targets; it does not dispatch until the workflow is enabled again.
|
||||
WorkflowDisabled bool `json:"workflow_disabled"`
|
||||
// LastOutcome is the binding's newest ledger row: the task it started or
|
||||
// the reason it started none.
|
||||
LastOutcome *storecontract.Dispatch `json:"last_outcome,omitempty"`
|
||||
}
|
||||
|
||||
func (s *Server) handleBindingsList(w http.ResponseWriter, r *http.Request) {
|
||||
if s.Bindings == nil {
|
||||
http.Error(w, "bindings not configured", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
bindings, err := s.Bindings.ListBindings(r.Context())
|
||||
if err != nil {
|
||||
s.Log.ErrorContext(r.Context(), "list bindings", "err", err)
|
||||
http.Error(w, "list bindings failed", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
unsigned, err := s.unsignedSources(r.Context())
|
||||
if err != nil {
|
||||
s.Log.ErrorContext(r.Context(), "list sources", "err", err)
|
||||
http.Error(w, "list bindings failed", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
enablement, _, err := s.workflowEnablement(r.Context())
|
||||
if err != nil {
|
||||
s.Log.ErrorContext(r.Context(), "workflow enablement", "err", err)
|
||||
http.Error(w, "list bindings failed", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
views := make([]bindingView, 0, len(bindings))
|
||||
for _, b := range bindings {
|
||||
if !listedIn(r, b.WorkspaceID) {
|
||||
continue
|
||||
}
|
||||
views = append(views, bindingView{
|
||||
Binding: b, Unsigned: unsigned[b.Matcher.Source], WorkflowDisabled: !enablement.Enabled(b.OrgID, b.Workflow),
|
||||
LastOutcome: s.lastOutcome(r.Context(), b.ID),
|
||||
})
|
||||
}
|
||||
writeJSON(w, map[string]any{"bindings": views})
|
||||
}
|
||||
|
||||
// lastOutcome returns a binding's newest dispatch, or nil when it has none or
|
||||
// the ledger is unreadable.
|
||||
func (s *Server) lastOutcome(ctx context.Context, bindingID string) *storecontract.Dispatch {
|
||||
if s.Dispatches == nil {
|
||||
return nil
|
||||
}
|
||||
rows, err := s.Dispatches.ListDispatches(ctx, storecontract.DispatchFilter{BindingID: bindingID, Limit: 1})
|
||||
if err != nil {
|
||||
s.Log.WarnContext(ctx, "binding last outcome", "binding", bindingID, "err", err)
|
||||
return nil
|
||||
}
|
||||
if len(rows) == 0 {
|
||||
return nil
|
||||
}
|
||||
return &rows[0]
|
||||
}
|
||||
|
||||
func (s *Server) handleBindingCreate(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.authorizeTaskMutation(w, r) {
|
||||
return
|
||||
}
|
||||
if s.Bindings == nil {
|
||||
http.Error(w, "bindings not configured", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
req, ok := decodeBody[bindingRequest](w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
b, ok := s.checkedBinding(w, r, "", req)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
id, err := s.Bindings.InsertBinding(r.Context(), b)
|
||||
if err != nil {
|
||||
s.Log.ErrorContext(r.Context(), "insert binding", "err", err)
|
||||
http.Error(w, "create binding failed", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
created, err := s.Bindings.GetBinding(r.Context(), id)
|
||||
if err != nil || created == nil {
|
||||
s.Log.ErrorContext(r.Context(), "get binding after insert", "err", err, "id", id)
|
||||
http.Error(w, "create binding failed", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
writeJSON(w, created)
|
||||
}
|
||||
|
||||
func (s *Server) handleBindingGet(w http.ResponseWriter, r *http.Request) {
|
||||
if s.Bindings == nil {
|
||||
http.Error(w, "bindings not configured", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
id := r.PathValue("id")
|
||||
if id == "" {
|
||||
http.Error(w, "invalid binding id", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
b, err := s.Bindings.GetBinding(r.Context(), id)
|
||||
if err != nil {
|
||||
s.Log.ErrorContext(r.Context(), "get binding", "err", err, "id", id)
|
||||
http.Error(w, "get binding failed", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
if b == nil {
|
||||
http.Error(w, "binding not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
writeJSON(w, b)
|
||||
}
|
||||
|
||||
// handleDispatches serves the newest dispatch ledger rows for the resource the
|
||||
// path names, linking bindings, captures and tasks to each other.
|
||||
// path names, linking bindings, captures and tasks to each other. Shared by
|
||||
// the bindings module and the captures/tasks routes, so it stays on Server.
|
||||
func (s *Server) handleDispatches(filterFor func(id string) (storecontract.DispatchFilter, bool)) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
if s.Dispatches == nil {
|
||||
@@ -175,193 +30,3 @@ func (s *Server) handleDispatches(filterFor func(id string) (storecontract.Dispa
|
||||
writeJSON(w, dispatches)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) handleBindingUpdate(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.authorizeTaskMutation(w, r) {
|
||||
return
|
||||
}
|
||||
if s.Bindings == nil {
|
||||
http.Error(w, "bindings not configured", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
id := r.PathValue("id")
|
||||
if id == "" {
|
||||
http.Error(w, "invalid binding id", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
req, ok := decodeBody[bindingRequest](w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
b, ok := s.checkedBinding(w, r, id, req)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if err := s.Bindings.UpdateBinding(r.Context(), b); err != nil {
|
||||
switch {
|
||||
case errors.Is(err, storecontract.ErrBindingNotFound):
|
||||
http.Error(w, "binding not found", http.StatusNotFound)
|
||||
default:
|
||||
s.Log.ErrorContext(r.Context(), "update binding", "err", err, "id", id)
|
||||
http.Error(w, "update binding failed", http.StatusInternalServerError)
|
||||
}
|
||||
return
|
||||
}
|
||||
updated, err := s.Bindings.GetBinding(r.Context(), id)
|
||||
if err != nil || updated == nil {
|
||||
s.Log.ErrorContext(r.Context(), "get binding after update", "err", err, "id", id)
|
||||
http.Error(w, "update binding failed", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
writeJSON(w, updated)
|
||||
}
|
||||
|
||||
func (s *Server) handleBindingDelete(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.authorizeTaskMutation(w, r) {
|
||||
return
|
||||
}
|
||||
if s.Bindings == nil {
|
||||
http.Error(w, "bindings not configured", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
id := r.PathValue("id")
|
||||
if id == "" {
|
||||
http.Error(w, "invalid binding id", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if err := s.Bindings.DeleteBinding(r.Context(), id); err != nil {
|
||||
if errors.Is(err, storecontract.ErrBindingNotFound) {
|
||||
http.Error(w, "binding not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
s.Log.ErrorContext(r.Context(), "delete binding", "err", err, "id", id)
|
||||
http.Error(w, "delete binding failed", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// handleBindingTransition serves one binding lifecycle command (approve,
|
||||
// pause, resume) and answers the binding as it now stands.
|
||||
func (s *Server) handleBindingTransition(verb string, apply func(storecontract.BindingStore, context.Context, string) error) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.authorizeTaskMutation(w, r) {
|
||||
return
|
||||
}
|
||||
if s.Bindings == nil {
|
||||
http.Error(w, "bindings not configured", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
id := r.PathValue("id")
|
||||
if id == "" {
|
||||
http.Error(w, "invalid binding id", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if err := apply(s.Bindings, r.Context(), id); err != nil {
|
||||
switch {
|
||||
case errors.Is(err, storecontract.ErrBindingNotFound):
|
||||
http.Error(w, "binding not found", http.StatusNotFound)
|
||||
case errors.Is(err, storecontract.ErrBindingTransition):
|
||||
http.Error(w, "binding cannot "+verb+" from its current state", http.StatusConflict)
|
||||
default:
|
||||
s.Log.ErrorContext(r.Context(), verb+" binding", "err", err, "id", id)
|
||||
http.Error(w, verb+" binding failed", http.StatusInternalServerError)
|
||||
}
|
||||
return
|
||||
}
|
||||
updated, err := s.Bindings.GetBinding(r.Context(), id)
|
||||
if err != nil || updated == nil {
|
||||
s.Log.ErrorContext(r.Context(), "get binding after "+verb, "err", err, "id", id)
|
||||
http.Error(w, verb+" binding failed", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
writeJSON(w, updated)
|
||||
}
|
||||
}
|
||||
|
||||
// checkedBinding builds the binding a create or update request describes and
|
||||
// refuses it, having written the error, unless it is well-formed, its mapping
|
||||
// exists, its filter compiles against the mapping's parameters, and its inputs
|
||||
// and repository satisfy the workflow it targets.
|
||||
func (s *Server) checkedBinding(w http.ResponseWriter, r *http.Request, id string, req bindingRequest) (binding.Binding, bool) {
|
||||
b := binding.Binding{
|
||||
ID: id,
|
||||
Name: req.Name,
|
||||
Matcher: req.Matcher,
|
||||
MappingID: req.MappingID,
|
||||
Filter: req.Filter,
|
||||
Workflow: req.Workflow,
|
||||
Owner: req.Owner,
|
||||
Repo: req.Repo,
|
||||
RepoParam: req.RepoParam,
|
||||
Inputs: req.Inputs,
|
||||
Status: binding.StatusPendingApproval,
|
||||
}
|
||||
if err := b.Validate(); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return binding.Binding{}, false
|
||||
}
|
||||
entry, found, err := s.workflowEntry(r.Context(), req.Workflow)
|
||||
if err != nil {
|
||||
http.Error(w, "workflow definitions unavailable", http.StatusServiceUnavailable)
|
||||
return binding.Binding{}, false
|
||||
}
|
||||
if !found {
|
||||
http.Error(w, "binding: workflow not found: "+req.Workflow, http.StatusBadRequest)
|
||||
return binding.Binding{}, false
|
||||
}
|
||||
enabled, err := s.bindingWorkflowEnabled(r.Context(), id, req.Workflow)
|
||||
if err != nil {
|
||||
http.Error(w, "workflow enablement unavailable", http.StatusServiceUnavailable)
|
||||
return binding.Binding{}, false
|
||||
}
|
||||
if !enabled {
|
||||
http.Error(w, "binding: workflow is disabled: "+req.Workflow, http.StatusConflict)
|
||||
return binding.Binding{}, false
|
||||
}
|
||||
iface, err := task.ParseWorkflowInterface(entry.YAML)
|
||||
if err != nil {
|
||||
http.Error(w, "binding: workflow "+req.Workflow+": "+err.Error(), http.StatusBadRequest)
|
||||
return binding.Binding{}, false
|
||||
}
|
||||
if s.Mappings == nil {
|
||||
http.Error(w, "mappings not configured", http.StatusServiceUnavailable)
|
||||
return binding.Binding{}, false
|
||||
}
|
||||
m, err := s.Mappings.GetMapping(r.Context(), b.MappingID)
|
||||
if err != nil {
|
||||
s.Log.ErrorContext(r.Context(), "get mapping for binding", "err", err, "mapping", b.MappingID)
|
||||
http.Error(w, "get mapping failed", http.StatusInternalServerError)
|
||||
return binding.Binding{}, false
|
||||
}
|
||||
if m == nil {
|
||||
http.Error(w, "binding: mapping not found: "+b.MappingID, http.StatusBadRequest)
|
||||
return binding.Binding{}, false
|
||||
}
|
||||
if _, err := binding.CompileFilter(b.Filter, m.Fields); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return binding.Binding{}, false
|
||||
}
|
||||
if err := b.CheckWorkflow(iface, m.Fields); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return binding.Binding{}, false
|
||||
}
|
||||
return b, true
|
||||
}
|
||||
|
||||
// bindingWorkflowEnabled reports whether the org owning binding id (the
|
||||
// default org for a binding not yet created) has workflow enabled.
|
||||
func (s *Server) bindingWorkflowEnabled(ctx context.Context, id, workflow string) (bool, error) {
|
||||
owner := org.DefaultOrgID
|
||||
if id != "" {
|
||||
existing, err := s.Bindings.GetBinding(ctx, id)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if existing != nil {
|
||||
owner = existing.OrgID
|
||||
}
|
||||
}
|
||||
enablement, _, err := s.workflowEnablement(ctx)
|
||||
return enablement.Enabled(owner, workflow), err
|
||||
}
|
||||
@@ -2,254 +2,21 @@ package webui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/access"
|
||||
"github.com/samcharles93/archie-core/internal/domain/org"
|
||||
"github.com/samcharles93/archie-core/internal/domain/source"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
)
|
||||
|
||||
// Shared source helpers: unsignedSources feeds the bindings list, recentRefusals
|
||||
// the sources list, listedIn every workspace-scoped list.
|
||||
|
||||
// Capture sources and their signing setting. A secret is returned only by the
|
||||
// two writes that generate it, so the operator can copy it into the sender;
|
||||
// every other read withholds it. Turning signing off is a request plus an
|
||||
// approval, both behind the same mutation gate that arms a binding.
|
||||
|
||||
func (s *Server) handleSourcesList(w http.ResponseWriter, r *http.Request) {
|
||||
if s.Sources == nil {
|
||||
http.Error(w, "sources not configured", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
list, err := s.Sources.ListSources(r.Context())
|
||||
if err != nil {
|
||||
s.Log.ErrorContext(r.Context(), "list sources", "err", err)
|
||||
http.Error(w, "list sources failed", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
list = slices.DeleteFunc(list, func(src source.Source) bool { return !listedIn(r, src.WorkspaceID) })
|
||||
for i := range list {
|
||||
list[i].Secret = ""
|
||||
}
|
||||
writeJSON(w, map[string]any{"sources": list, "refusals": s.recentRefusals(r)})
|
||||
}
|
||||
|
||||
func (s *Server) handleSourceCreate(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.authorizeTaskMutation(w, r) {
|
||||
return
|
||||
}
|
||||
if s.Sources == nil {
|
||||
http.Error(w, "sources not configured", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
Path string `json:"path"`
|
||||
// Workspace is the caller's org workspace to create it in; empty is
|
||||
// the default one.
|
||||
Workspace org.WorkspaceID `json:"workspace"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
http.Error(w, "invalid request body: "+err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if !s.authorizeCreateIn(w, r, access.KindSource, req.Workspace) {
|
||||
return
|
||||
}
|
||||
src, err := source.New(req.Path)
|
||||
if errors.Is(err, source.ErrInvalidPath) || errors.Is(err, source.ErrReservedPath) {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if err == nil {
|
||||
src.WorkspaceID = req.Workspace
|
||||
err = s.Sources.InsertSource(r.Context(), src)
|
||||
}
|
||||
if err != nil {
|
||||
s.sourceError(w, "create source", err)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
writeJSON(w, src)
|
||||
}
|
||||
|
||||
// handleSourceSigning turns signing on at once, or requests turning it off.
|
||||
func (s *Server) handleSourceSigning(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
Signed bool `json:"signed"`
|
||||
}
|
||||
if !s.authorizeTaskMutation(w, r) {
|
||||
return
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
http.Error(w, "invalid request body: "+err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
transition := (*source.Source).RequestUnsigned
|
||||
if req.Signed {
|
||||
transition = (*source.Source).RequireSigning
|
||||
}
|
||||
s.transitionSource(w, r, transition)
|
||||
}
|
||||
|
||||
func (s *Server) handleSourceApproveUnsigned(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.authorizeTaskMutation(w, r) {
|
||||
return
|
||||
}
|
||||
s.transitionSource(w, r, (*source.Source).ApproveUnsigned)
|
||||
}
|
||||
|
||||
// transitionSource applies one domain signing transition and writes it with
|
||||
// the state it was decided from, so a concurrent change is refused.
|
||||
func (s *Server) transitionSource(w http.ResponseWriter, r *http.Request, transition func(*source.Source) error) {
|
||||
src, ok := s.loadSource(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
from := src.Signing
|
||||
if err := transition(src); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusConflict)
|
||||
return
|
||||
}
|
||||
if err := s.Sources.SetSourceSigning(r.Context(), src.Path, from, src.Signing); err != nil {
|
||||
s.sourceError(w, "set source signing", err)
|
||||
return
|
||||
}
|
||||
src.Secret = ""
|
||||
writeJSON(w, src)
|
||||
}
|
||||
|
||||
// handleSourceSecret generates a new secret and returns it once.
|
||||
func (s *Server) handleSourceSecret(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.authorizeTaskMutation(w, r) {
|
||||
return
|
||||
}
|
||||
src, ok := s.loadSource(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
secret, err := source.NewSecret()
|
||||
if err == nil {
|
||||
err = s.Sources.SetSourceSecret(r.Context(), src.Path, secret)
|
||||
}
|
||||
if err != nil {
|
||||
s.sourceError(w, "set source secret", err)
|
||||
return
|
||||
}
|
||||
src.Secret = secret
|
||||
writeJSON(w, src)
|
||||
}
|
||||
|
||||
// handleSourceName relabels a source; its path does not change.
|
||||
func (s *Server) handleSourceName(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.authorizeTaskMutation(w, r) {
|
||||
return
|
||||
}
|
||||
src, ok := s.loadSource(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var request struct {
|
||||
Name string `json:"name"`
|
||||
}
|
||||
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4<<10)).Decode(&request); err != nil {
|
||||
http.Error(w, "invalid source name", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
src.Name = strings.TrimSpace(request.Name)
|
||||
if err := s.Sources.SetSourceName(r.Context(), src.Path, src.Name); err != nil {
|
||||
s.sourceError(w, "set source name", err)
|
||||
return
|
||||
}
|
||||
src.Secret = ""
|
||||
writeJSON(w, src)
|
||||
}
|
||||
|
||||
// handleSourceDeliveryHeader sets the header that names a source's
|
||||
// deliveries, so a sender's retry dispatches no second run.
|
||||
func (s *Server) handleSourceDeliveryHeader(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.authorizeTaskMutation(w, r) {
|
||||
return
|
||||
}
|
||||
src, ok := s.loadSource(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var request struct {
|
||||
Header string `json:"header"`
|
||||
}
|
||||
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4<<10)).Decode(&request); err != nil {
|
||||
http.Error(w, "invalid delivery header", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
header, err := source.DeliveryHeader(request.Header)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
src.DeliveryHeader = header
|
||||
if err := s.Sources.SetSourceDeliveryHeader(r.Context(), src.Path, header); err != nil {
|
||||
s.sourceError(w, "set source delivery header", err)
|
||||
return
|
||||
}
|
||||
src.Secret = ""
|
||||
writeJSON(w, src)
|
||||
}
|
||||
|
||||
// handleSourceDelete deletes a source no armed binding fires on.
|
||||
func (s *Server) handleSourceDelete(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.authorizeTaskMutation(w, r) {
|
||||
return
|
||||
}
|
||||
if s.Sources == nil {
|
||||
http.Error(w, "sources not configured", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
if err := s.Sources.DeleteSource(r.Context(), r.PathValue("path")); err != nil {
|
||||
s.sourceError(w, "delete source", err)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (s *Server) loadSource(w http.ResponseWriter, r *http.Request) (*source.Source, bool) {
|
||||
if s.Sources == nil {
|
||||
http.Error(w, "sources not configured", http.StatusServiceUnavailable)
|
||||
return nil, false
|
||||
}
|
||||
src, err := s.Sources.GetSource(r.Context(), r.PathValue("path"))
|
||||
if err != nil {
|
||||
s.sourceError(w, "get source", err)
|
||||
return nil, false
|
||||
}
|
||||
if src == nil {
|
||||
http.Error(w, "source not found", http.StatusNotFound)
|
||||
return nil, false
|
||||
}
|
||||
return src, true
|
||||
}
|
||||
|
||||
func (s *Server) sourceError(w http.ResponseWriter, what string, err error) {
|
||||
switch {
|
||||
case errors.Is(err, storecontract.ErrSourcePathTaken):
|
||||
http.Error(w, "source path already taken", http.StatusConflict)
|
||||
case errors.Is(err, storecontract.ErrSourceSigningStale):
|
||||
http.Error(w, "source signing changed; reload and retry", http.StatusConflict)
|
||||
case errors.Is(err, storecontract.ErrSourceNotFound):
|
||||
http.Error(w, "source not found", http.StatusNotFound)
|
||||
case errors.Is(err, org.ErrInvalidWorkspace):
|
||||
http.Error(w, "that workspace is not one of this org's", http.StatusBadRequest)
|
||||
case errors.Is(err, storecontract.ErrSourceInUse):
|
||||
http.Error(w, "an armed binding fires on this source; pause or delete it first", http.StatusConflict)
|
||||
default:
|
||||
s.Log.Error(what, "err", err)
|
||||
http.Error(w, what+" failed", http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
||||
// unsignedSources is the set of source paths approved to take unsigned
|
||||
// events. With no source store nothing is unsigned.
|
||||
func (s *Server) unsignedSources(ctx context.Context) (map[string]bool, error) {
|
||||
|
||||
@@ -7,12 +7,14 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"maps"
|
||||
"mime"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"google.golang.org/grpc/codes"
|
||||
@@ -21,6 +23,7 @@ import (
|
||||
controlpb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
|
||||
"github.com/samcharles93/archie-core/internal/domain/access"
|
||||
"github.com/samcharles93/archie-core/internal/domain/audit"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
|
||||
"github.com/samcharles93/archie-core/internal/ratelimit"
|
||||
)
|
||||
|
||||
@@ -116,11 +119,46 @@ type auditResponse struct {
|
||||
Facets *auditFacetsView `json:"facets,omitempty"`
|
||||
}
|
||||
|
||||
// auditAPI owns the /api/audit routes. exporting admits one export per
|
||||
// identity and exportRate bounds how many each identity starts an hour; an
|
||||
// export is also bounded by its explicit range, a five-minute deadline and a
|
||||
// page cap.
|
||||
type auditAPI struct {
|
||||
audit audit.Store
|
||||
controlPlane controlpb.ControlPlaneServiceClient
|
||||
log *slog.Logger
|
||||
actorNames func(context.Context) func(string) string
|
||||
workflowDefinitions func(context.Context) ([]task.Definition, error)
|
||||
|
||||
exportRate *ratelimit.Limiter
|
||||
exportMu sync.Mutex
|
||||
exporting map[string]bool
|
||||
}
|
||||
|
||||
func newAuditAPI(s *Server) *auditAPI {
|
||||
return &auditAPI{
|
||||
audit: s.Audit,
|
||||
controlPlane: s.ControlPlane,
|
||||
log: s.Log,
|
||||
actorNames: s.actorNames,
|
||||
workflowDefinitions: newWorkflowsAPI(s).workflowDefinitions,
|
||||
exportRate: ratelimit.New(auditExportWindow, auditExportPerHour),
|
||||
exporting: map[string]bool{},
|
||||
}
|
||||
}
|
||||
|
||||
func (a *auditAPI) logf(msg string, args ...any) { warnf(a.log, msg, args...) }
|
||||
|
||||
func (a *auditAPI) register(mux *http.ServeMux) {
|
||||
mux.HandleFunc("GET /api/audit", a.handleAudit)
|
||||
mux.HandleFunc("GET /api/audit/export", a.handleAuditExport)
|
||||
}
|
||||
|
||||
// handleAudit is GET /api/audit: one page of the org-scoped feed. The org and
|
||||
// the reader's authority come from the authenticated principal in the request
|
||||
// context; the query string never names an org.
|
||||
func (s *Server) handleAudit(w http.ResponseWriter, r *http.Request) {
|
||||
if s.Audit == nil {
|
||||
func (a *auditAPI) handleAudit(w http.ResponseWriter, r *http.Request) {
|
||||
if a.audit == nil {
|
||||
http.Error(w, "audit feed unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
@@ -133,12 +171,12 @@ func (s *Server) handleAudit(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, firstLine(err.Error()), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
page, err := s.Audit.ListAudit(r.Context(), filter, cursor, limit)
|
||||
page, err := a.audit.ListAudit(r.Context(), filter, cursor, limit)
|
||||
if err != nil {
|
||||
writeAuditError(w, err)
|
||||
return
|
||||
}
|
||||
labels, settings := s.auditLabels(r.Context())
|
||||
labels, settings := a.auditLabels(r.Context())
|
||||
records := make([]auditRecordView, 0, len(page.Entries))
|
||||
for _, entry := range page.Entries {
|
||||
records = append(records, auditRecord(entry, labels))
|
||||
@@ -159,8 +197,8 @@ func (s *Server) handleAudit(w http.ResponseWriter, r *http.Request) {
|
||||
// handleAuditExport is GET /api/audit/export?format=csv|json with the feed's
|
||||
// filters. It requires an explicit range of at most a year and streams rows
|
||||
// page by page.
|
||||
func (s *Server) handleAuditExport(w http.ResponseWriter, r *http.Request) {
|
||||
if s.Audit == nil {
|
||||
func (a *auditAPI) handleAuditExport(w http.ResponseWriter, r *http.Request) {
|
||||
if a.audit == nil {
|
||||
http.Error(w, "audit feed unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
@@ -185,12 +223,12 @@ func (s *Server) handleAuditExport(w http.ResponseWriter, r *http.Request) {
|
||||
identity := auditExportIdentity(r.Context())
|
||||
// Take the guard before charging the budget: a request rejected because
|
||||
// the same identity is already exporting must cost no allowance.
|
||||
if !s.beginAuditExport(identity) {
|
||||
if !a.beginAuditExport(identity) {
|
||||
http.Error(w, "an audit export is already running for this identity", http.StatusTooManyRequests)
|
||||
return
|
||||
}
|
||||
defer s.endAuditExport(identity)
|
||||
if !s.auditExportLimiter().Allow("audit-export", identity) {
|
||||
defer a.endAuditExport(identity)
|
||||
if !a.exportRate.Allow("audit-export", identity) {
|
||||
http.Error(w, "too many audit exports; try again later", http.StatusTooManyRequests)
|
||||
return
|
||||
}
|
||||
@@ -199,41 +237,41 @@ func (s *Server) handleAuditExport(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
// Count before any header is written: a match over the cap is the
|
||||
// caller's problem to narrow, not a download that ends early.
|
||||
if !s.auditExportWithinBudget(ctx, w, filter) {
|
||||
if !a.auditExportWithinBudget(ctx, w, filter) {
|
||||
return
|
||||
}
|
||||
|
||||
// Fetch the first page before setting download headers: a failure here is
|
||||
// still a normal error response, not a truncated file.
|
||||
first, err := s.Audit.ListAudit(ctx, filter, audit.Cursor{}, auditExportPageSize)
|
||||
first, err := a.audit.ListAudit(ctx, filter, audit.Cursor{}, auditExportPageSize)
|
||||
if err != nil {
|
||||
writeAuditError(w, err)
|
||||
return
|
||||
}
|
||||
writeAuditExportHeaders(w, format)
|
||||
|
||||
labels, _ := s.auditLabels(ctx)
|
||||
labels, _ := a.auditLabels(ctx)
|
||||
flush := func() {}
|
||||
if flusher, ok := w.(http.Flusher); ok {
|
||||
flush = flusher.Flush
|
||||
}
|
||||
var rows int64
|
||||
if format == "csv" {
|
||||
rows, err = s.exportAuditCSV(ctx, filter, first, labels, w, flush)
|
||||
rows, err = a.exportAuditCSV(ctx, filter, first, labels, w, flush)
|
||||
} else {
|
||||
rows, err = s.exportAuditJSON(ctx, filter, first, labels, w, flush)
|
||||
rows, err = a.exportAuditJSON(ctx, filter, first, labels, w, flush)
|
||||
}
|
||||
if err != nil {
|
||||
// Headers and status are already on the wire, so no error status is
|
||||
// left to send. Abort the connection so the client sees a failed
|
||||
// download rather than a silently short file.
|
||||
s.logf("audit export failed", "format", format, "err", err)
|
||||
a.logf("audit export failed", "format", format, "err", err)
|
||||
panic(http.ErrAbortHandler)
|
||||
}
|
||||
// The file is complete; the trail row is bookkeeping, so a failed write
|
||||
// is logged rather than turning a delivered export into a failed one.
|
||||
if err := s.Audit.RecordAuditExport(r.Context(), format, filter.Hash(), rows); err != nil {
|
||||
s.logf("record audit export", "format", format, "err", err)
|
||||
if err := a.audit.RecordAuditExport(r.Context(), format, filter.Hash(), rows); err != nil {
|
||||
a.logf("record audit export", "format", format, "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -241,8 +279,8 @@ func (s *Server) handleAuditExport(w http.ResponseWriter, r *http.Request) {
|
||||
// cap, answering before any header is written so the client never receives a
|
||||
// truncated file it cannot tell from a complete one. A feed error is written
|
||||
// with the same status mapping as a page read.
|
||||
func (s *Server) auditExportWithinBudget(ctx context.Context, w http.ResponseWriter, filter audit.Filter) bool {
|
||||
count, err := s.Audit.CountAudit(ctx, filter)
|
||||
func (a *auditAPI) auditExportWithinBudget(ctx context.Context, w http.ResponseWriter, filter audit.Filter) bool {
|
||||
count, err := a.audit.CountAudit(ctx, filter)
|
||||
if err != nil {
|
||||
writeAuditError(w, err)
|
||||
return false
|
||||
@@ -301,12 +339,12 @@ func writeAuditExportHeaders(w http.ResponseWriter, format string) {
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
}
|
||||
|
||||
func (s *Server) exportAuditCSV(ctx context.Context, filter audit.Filter, first audit.Page, labels *auditLabels, w io.Writer, flush func()) (int64, error) {
|
||||
func (a *auditAPI) exportAuditCSV(ctx context.Context, filter audit.Filter, first audit.Page, labels *auditLabels, w io.Writer, flush func()) (int64, error) {
|
||||
writer := csv.NewWriter(w)
|
||||
if err := writer.Write(auditCSVHeader); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
rows, err := s.walkAudit(ctx, filter, first, func(entry audit.Entry) error {
|
||||
rows, err := a.walkAudit(ctx, filter, first, func(entry audit.Entry) error {
|
||||
return writer.Write(auditCSVRow(auditRecord(entry, labels)))
|
||||
}, func() {
|
||||
writer.Flush()
|
||||
@@ -319,13 +357,13 @@ func (s *Server) exportAuditCSV(ctx context.Context, filter audit.Filter, first
|
||||
return rows, err
|
||||
}
|
||||
|
||||
func (s *Server) exportAuditJSON(ctx context.Context, filter audit.Filter, first audit.Page, labels *auditLabels, w io.Writer, flush func()) (int64, error) {
|
||||
func (a *auditAPI) exportAuditJSON(ctx context.Context, filter audit.Filter, first audit.Page, labels *auditLabels, w io.Writer, flush func()) (int64, error) {
|
||||
if _, err := io.WriteString(w, "["); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
encoder := json.NewEncoder(w)
|
||||
firstRecord := true
|
||||
rows, err := s.walkAudit(ctx, filter, first, func(entry audit.Entry) error {
|
||||
rows, err := a.walkAudit(ctx, filter, first, func(entry audit.Entry) error {
|
||||
if !firstRecord {
|
||||
if _, err := io.WriteString(w, ","); err != nil {
|
||||
return err
|
||||
@@ -346,7 +384,7 @@ func (s *Server) exportAuditJSON(ctx context.Context, filter audit.Filter, first
|
||||
// walkAudit streams every entry of the window in feed order and returns how
|
||||
// many it emitted. It starts from the already-fetched first page so the caller
|
||||
// could answer an error before any byte of the download was written.
|
||||
func (s *Server) walkAudit(ctx context.Context, filter audit.Filter, first audit.Page, emit func(audit.Entry) error, afterPage func()) (int64, error) {
|
||||
func (a *auditAPI) walkAudit(ctx context.Context, filter audit.Filter, first audit.Page, emit func(audit.Entry) error, afterPage func()) (int64, error) {
|
||||
page := first
|
||||
pages := 1
|
||||
var rows int64
|
||||
@@ -371,7 +409,7 @@ func (s *Server) walkAudit(ctx context.Context, filter audit.Filter, first audit
|
||||
if !ok {
|
||||
return rows, errAuditExportCursor
|
||||
}
|
||||
next, err := s.Audit.ListAudit(ctx, filter, cursor, auditExportPageSize)
|
||||
next, err := a.audit.ListAudit(ctx, filter, cursor, auditExportPageSize)
|
||||
if err != nil {
|
||||
return rows, err
|
||||
}
|
||||
@@ -472,10 +510,10 @@ func (l *auditLabels) workflow(id string) string {
|
||||
// auditLabels builds the label resolver and the settings-kind facet in one
|
||||
// catalog read. A failed catalog read degrades labels to their ids; it never
|
||||
// fails the feed.
|
||||
func (s *Server) auditLabels(ctx context.Context) (*auditLabels, []auditSettingsKind) {
|
||||
labels := &auditLabels{actorName: s.actorNames(ctx), titles: map[string]string{}}
|
||||
func (a *auditAPI) auditLabels(ctx context.Context) (*auditLabels, []auditSettingsKind) {
|
||||
labels := &auditLabels{actorName: a.actorNames(ctx), titles: map[string]string{}}
|
||||
settings := []auditSettingsKind{}
|
||||
for _, resource := range s.auditCatalogResources(ctx) {
|
||||
for _, resource := range a.auditCatalogResources(ctx) {
|
||||
if resource.GetTitle() != "" {
|
||||
labels.titles[resource.GetKind()] = resource.GetTitle()
|
||||
}
|
||||
@@ -486,7 +524,7 @@ func (s *Server) auditLabels(ctx context.Context) (*auditLabels, []auditSettings
|
||||
}
|
||||
}
|
||||
labels.workflowFn = func() map[string]string {
|
||||
definitions, err := s.workflowDefinitions(ctx)
|
||||
definitions, err := a.workflowDefinitions(ctx)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
@@ -502,11 +540,11 @@ func (s *Server) auditLabels(ctx context.Context) (*auditLabels, []auditSettings
|
||||
// auditCatalogResources reads the control-plane catalogue once. A missing
|
||||
// control plane or a failed read leaves labels at their ids rather than
|
||||
// failing the feed.
|
||||
func (s *Server) auditCatalogResources(ctx context.Context) []*controlpb.ResourceDescriptor {
|
||||
if s.ControlPlane == nil {
|
||||
func (a *auditAPI) auditCatalogResources(ctx context.Context) []*controlpb.ResourceDescriptor {
|
||||
if a.controlPlane == nil {
|
||||
return nil
|
||||
}
|
||||
catalog, err := s.ControlPlane.Catalog(ctx, &controlpb.CatalogRequest{})
|
||||
catalog, err := a.controlPlane.Catalog(ctx, &controlpb.CatalogRequest{})
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
@@ -639,33 +677,23 @@ func auditExportIdentity(ctx context.Context) string {
|
||||
return "unknown"
|
||||
}
|
||||
|
||||
func (s *Server) auditExportLimiter() *ratelimit.Limiter {
|
||||
s.auditExportOnce.Do(func() {
|
||||
s.auditExportRate = ratelimit.New(auditExportWindow, auditExportPerHour)
|
||||
})
|
||||
return s.auditExportRate
|
||||
}
|
||||
|
||||
// beginAuditExport admits one export per identity. The guard is per identity,
|
||||
// not process-wide: one person's long export must not stop another person in
|
||||
// another org from taking their own.
|
||||
func (s *Server) beginAuditExport(identity string) bool {
|
||||
s.auditExportMu.Lock()
|
||||
defer s.auditExportMu.Unlock()
|
||||
if s.auditExporting == nil {
|
||||
s.auditExporting = make(map[string]bool)
|
||||
}
|
||||
if s.auditExporting[identity] {
|
||||
func (a *auditAPI) beginAuditExport(identity string) bool {
|
||||
a.exportMu.Lock()
|
||||
defer a.exportMu.Unlock()
|
||||
if a.exporting[identity] {
|
||||
return false
|
||||
}
|
||||
s.auditExporting[identity] = true
|
||||
a.exporting[identity] = true
|
||||
return true
|
||||
}
|
||||
|
||||
func (s *Server) endAuditExport(identity string) {
|
||||
s.auditExportMu.Lock()
|
||||
delete(s.auditExporting, identity)
|
||||
s.auditExportMu.Unlock()
|
||||
func (a *auditAPI) endAuditExport(identity string) {
|
||||
a.exportMu.Lock()
|
||||
delete(a.exporting, identity)
|
||||
a.exportMu.Unlock()
|
||||
}
|
||||
|
||||
var auditCSVHeader = []string{
|
||||
@@ -77,7 +77,7 @@ func TestAuditErrorMapping(t *testing.T) {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
srv := &Server{Audit: auditStub{err: tt.err}}
|
||||
rec := httptest.NewRecorder()
|
||||
srv.handleAudit(rec, httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/audit", nil))
|
||||
newAuditAPI(srv).handleAudit(rec, httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/audit", nil))
|
||||
if rec.Code != tt.want {
|
||||
t.Fatalf("status = %d, want %d", rec.Code, tt.want)
|
||||
}
|
||||
@@ -90,7 +90,7 @@ func TestAuditErrorMapping(t *testing.T) {
|
||||
|
||||
func TestAuditUnavailableWithoutFeed(t *testing.T) {
|
||||
rec := httptest.NewRecorder()
|
||||
(&Server{}).handleAudit(rec, httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/audit", nil))
|
||||
newAuditAPI(&Server{}).handleAudit(rec, httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/audit", nil))
|
||||
if rec.Code != http.StatusServiceUnavailable {
|
||||
t.Fatalf("status = %d, want %d", rec.Code, http.StatusServiceUnavailable)
|
||||
}
|
||||
@@ -104,7 +104,7 @@ func TestAuditExportRefusesOverTheRowCap(t *testing.T) {
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet,
|
||||
"/api/audit/export?format=json&from=2026-01-01T00:00:00Z&to=2026-01-02T00:00:00Z", nil)
|
||||
rec := httptest.NewRecorder()
|
||||
srv.handleAuditExport(rec, req)
|
||||
newAuditAPI(srv).handleAuditExport(rec, req)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status = %d, want %d body=%s", rec.Code, http.StatusBadRequest, rec.Body.String())
|
||||
}
|
||||
@@ -119,7 +119,7 @@ func TestSharedTokenOperatorPostsPersonalToken(t *testing.T) {
|
||||
Principals: stubPrincipals(true),
|
||||
PersonalTokens: tokens,
|
||||
}
|
||||
handler := s.requireToken(s.authorize(http.HandlerFunc(s.handlePersonalTokenCreate)))
|
||||
handler := s.requireToken(s.authorize(http.HandlerFunc(newIdentitiesAPI(s).handlePersonalTokenCreate)))
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/api/tokens", strings.NewReader(`{"name":"ci","days":30}`))
|
||||
req.Header.Set("Authorization", "Bearer shared")
|
||||
@@ -260,11 +260,11 @@ func TestPersonalTokensWithoutPerson(t *testing.T) {
|
||||
rec := httptest.NewRecorder()
|
||||
switch method {
|
||||
case http.MethodGet:
|
||||
s.handlePersonalTokensList(rec, req)
|
||||
newIdentitiesAPI(s).handlePersonalTokensList(rec, req)
|
||||
case http.MethodPost:
|
||||
s.handlePersonalTokenCreate(rec, req)
|
||||
newIdentitiesAPI(s).handlePersonalTokenCreate(rec, req)
|
||||
case http.MethodDelete:
|
||||
s.handlePersonalTokenRevoke(rec, req)
|
||||
newIdentitiesAPI(s).handlePersonalTokenRevoke(rec, req)
|
||||
}
|
||||
if method == http.MethodGet {
|
||||
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"available":false`) {
|
||||
|
||||
@@ -0,0 +1,388 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/binding"
|
||||
"github.com/samcharles93/archie-core/internal/domain/org"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
|
||||
)
|
||||
|
||||
// bindingsAPI owns the /api/bindings routes and the binding dispatch
|
||||
// sub-resource. The composition root constructs it only when the binding
|
||||
// store is configured; otherwise Server mounts a 503 stub, so a.bindings is
|
||||
// always non-nil here. dispatches and mappings stay optional: lastOutcome
|
||||
// degrades to nil and checkedBinding answers 503, as before.
|
||||
type bindingsAPI struct {
|
||||
bindings storecontract.BindingStore
|
||||
dispatches storecontract.DispatchLedger
|
||||
mappings storecontract.MappingStore
|
||||
log *slog.Logger
|
||||
|
||||
authorizeTaskMutation func(http.ResponseWriter, *http.Request) bool
|
||||
workflowEntry func(context.Context, string) (task.WorkflowDefinitionEntry, bool, error)
|
||||
workflowEnablement func(context.Context) (task.WorkflowEnablement, int64, error)
|
||||
unsignedSources func(context.Context) (map[string]bool, error)
|
||||
dispatchesFor func(func(string) (storecontract.DispatchFilter, bool)) http.HandlerFunc
|
||||
}
|
||||
|
||||
func newBindingsAPI(s *Server) *bindingsAPI {
|
||||
return &bindingsAPI{
|
||||
bindings: s.Bindings,
|
||||
dispatches: s.Dispatches,
|
||||
mappings: s.Mappings,
|
||||
log: s.Log,
|
||||
authorizeTaskMutation: s.authorizeTaskMutation,
|
||||
workflowEntry: newWorkflowsAPI(s).workflowEntry,
|
||||
workflowEnablement: newWorkflowsAPI(s).workflowEnablement,
|
||||
unsignedSources: s.unsignedSources,
|
||||
dispatchesFor: s.handleDispatches,
|
||||
}
|
||||
}
|
||||
|
||||
// bindingsRoutes lists the method+path patterns the bindings module owns, so
|
||||
// the 503 stub mounts exactly the same routes.
|
||||
var bindingsRoutes = []string{
|
||||
"GET /api/bindings",
|
||||
"POST /api/bindings",
|
||||
"GET /api/bindings/{id}",
|
||||
"PATCH /api/bindings/{id}",
|
||||
"DELETE /api/bindings/{id}",
|
||||
"POST /api/bindings/{id}/approve",
|
||||
"POST /api/bindings/{id}/pause",
|
||||
"POST /api/bindings/{id}/resume",
|
||||
"GET /api/bindings/{id}/dispatches",
|
||||
}
|
||||
|
||||
// notConfigured answers every request with msg and 503, matching what the
|
||||
// handlers did when their store field was nil.
|
||||
func notConfigured(msg string) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, _ *http.Request) {
|
||||
http.Error(w, msg, http.StatusServiceUnavailable)
|
||||
}
|
||||
}
|
||||
|
||||
func (a *bindingsAPI) register(mux *http.ServeMux) {
|
||||
mux.HandleFunc("GET /api/bindings", a.handleBindingsList)
|
||||
mux.HandleFunc("POST /api/bindings", a.handleBindingCreate)
|
||||
mux.HandleFunc("GET /api/bindings/{id}", a.handleBindingGet)
|
||||
mux.HandleFunc("PATCH /api/bindings/{id}", a.handleBindingUpdate)
|
||||
mux.HandleFunc("DELETE /api/bindings/{id}", a.handleBindingDelete)
|
||||
mux.HandleFunc("POST /api/bindings/{id}/approve", a.handleBindingTransition("approve", storecontract.BindingStore.ApproveBinding))
|
||||
mux.HandleFunc("POST /api/bindings/{id}/pause", a.handleBindingTransition("pause", storecontract.BindingStore.PauseBinding))
|
||||
mux.HandleFunc("POST /api/bindings/{id}/resume", a.handleBindingTransition("resume", storecontract.BindingStore.ResumeBinding))
|
||||
mux.HandleFunc("GET /api/bindings/{id}/dispatches", a.dispatchesFor(func(id string) (storecontract.DispatchFilter, bool) {
|
||||
return storecontract.DispatchFilter{BindingID: id}, id != ""
|
||||
}))
|
||||
}
|
||||
|
||||
// bindingRequest is the wire shape POST /api/bindings and
|
||||
// PATCH /api/bindings/{id} both accept. ID/Version/Status/CreatedAt/UpdatedAt
|
||||
// are server-assigned (or server-driven), never taken from the request body.
|
||||
type bindingRequest struct {
|
||||
Name string `json:"name"`
|
||||
Matcher binding.Matcher `json:"matcher"`
|
||||
MappingID string `json:"mapping_id"`
|
||||
Filter string `json:"filter"`
|
||||
Workflow string `json:"workflow"`
|
||||
// Owner and Repo optionally pin the binding to one configured repo,
|
||||
// for multi-repo deployments. Both empty is valid (falls back to the
|
||||
// daemon's single-configured-repo behaviour); binding.Validate
|
||||
// rejects setting only one.
|
||||
Owner string `json:"owner"`
|
||||
Repo string `json:"repo"`
|
||||
// RepoParam takes the repository from a mapped parameter instead.
|
||||
RepoParam string `json:"repo_param"`
|
||||
Inputs map[string]binding.InputSource `json:"inputs"`
|
||||
}
|
||||
|
||||
// bindingView is a listed binding with its source's signing state, so the
|
||||
// list can flag a binding that dispatches unsigned events.
|
||||
type bindingView struct {
|
||||
binding.Binding
|
||||
Unsigned bool `json:"unsigned"`
|
||||
// WorkflowDisabled marks a binding whose org has disabled the workflow it
|
||||
// targets; it does not dispatch until the workflow is enabled again.
|
||||
WorkflowDisabled bool `json:"workflow_disabled"`
|
||||
// LastOutcome is the binding's newest ledger row: the task it started or
|
||||
// the reason it started none.
|
||||
LastOutcome *storecontract.Dispatch `json:"last_outcome,omitempty"`
|
||||
}
|
||||
|
||||
func (a *bindingsAPI) handleBindingsList(w http.ResponseWriter, r *http.Request) {
|
||||
bindings, err := a.bindings.ListBindings(r.Context())
|
||||
if err != nil {
|
||||
a.log.ErrorContext(r.Context(), "list bindings", "err", err)
|
||||
http.Error(w, "list bindings failed", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
unsigned, err := a.unsignedSources(r.Context())
|
||||
if err != nil {
|
||||
a.log.ErrorContext(r.Context(), "list sources", "err", err)
|
||||
http.Error(w, "list bindings failed", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
enablement, _, err := a.workflowEnablement(r.Context())
|
||||
if err != nil {
|
||||
a.log.ErrorContext(r.Context(), "workflow enablement", "err", err)
|
||||
http.Error(w, "list bindings failed", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
views := make([]bindingView, 0, len(bindings))
|
||||
for _, b := range bindings {
|
||||
if !listedIn(r, b.WorkspaceID) {
|
||||
continue
|
||||
}
|
||||
views = append(views, bindingView{
|
||||
Binding: b, Unsigned: unsigned[b.Matcher.Source], WorkflowDisabled: !enablement.Enabled(b.OrgID, b.Workflow),
|
||||
LastOutcome: a.lastOutcome(r.Context(), b.ID),
|
||||
})
|
||||
}
|
||||
writeJSON(w, map[string]any{"bindings": views})
|
||||
}
|
||||
|
||||
// lastOutcome returns a binding's newest dispatch, or nil when it has none or
|
||||
// the ledger is unreadable.
|
||||
func (a *bindingsAPI) lastOutcome(ctx context.Context, bindingID string) *storecontract.Dispatch {
|
||||
if a.dispatches == nil {
|
||||
return nil
|
||||
}
|
||||
rows, err := a.dispatches.ListDispatches(ctx, storecontract.DispatchFilter{BindingID: bindingID, Limit: 1})
|
||||
if err != nil {
|
||||
a.log.WarnContext(ctx, "binding last outcome", "binding", bindingID, "err", err)
|
||||
return nil
|
||||
}
|
||||
if len(rows) == 0 {
|
||||
return nil
|
||||
}
|
||||
return &rows[0]
|
||||
}
|
||||
|
||||
func (a *bindingsAPI) handleBindingCreate(w http.ResponseWriter, r *http.Request) {
|
||||
if !a.authorizeTaskMutation(w, r) {
|
||||
return
|
||||
}
|
||||
req, ok := decodeBody[bindingRequest](w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
b, ok := a.checkedBinding(w, r, "", req)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
id, err := a.bindings.InsertBinding(r.Context(), b)
|
||||
if err != nil {
|
||||
a.log.ErrorContext(r.Context(), "insert binding", "err", err)
|
||||
http.Error(w, "create binding failed", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
created, err := a.bindings.GetBinding(r.Context(), id)
|
||||
if err != nil || created == nil {
|
||||
a.log.ErrorContext(r.Context(), "get binding after insert", "err", err, "id", id)
|
||||
http.Error(w, "create binding failed", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
writeJSON(w, created)
|
||||
}
|
||||
|
||||
func (a *bindingsAPI) handleBindingGet(w http.ResponseWriter, r *http.Request) {
|
||||
id := r.PathValue("id")
|
||||
if id == "" {
|
||||
http.Error(w, "invalid binding id", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
b, err := a.bindings.GetBinding(r.Context(), id)
|
||||
if err != nil {
|
||||
a.log.ErrorContext(r.Context(), "get binding", "err", err, "id", id)
|
||||
http.Error(w, "get binding failed", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
if b == nil {
|
||||
http.Error(w, "binding not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
writeJSON(w, b)
|
||||
}
|
||||
|
||||
func (a *bindingsAPI) handleBindingUpdate(w http.ResponseWriter, r *http.Request) {
|
||||
if !a.authorizeTaskMutation(w, r) {
|
||||
return
|
||||
}
|
||||
id := r.PathValue("id")
|
||||
if id == "" {
|
||||
http.Error(w, "invalid binding id", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
req, ok := decodeBody[bindingRequest](w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
b, ok := a.checkedBinding(w, r, id, req)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if err := a.bindings.UpdateBinding(r.Context(), b); err != nil {
|
||||
switch {
|
||||
case errors.Is(err, storecontract.ErrBindingNotFound):
|
||||
http.Error(w, "binding not found", http.StatusNotFound)
|
||||
default:
|
||||
a.log.ErrorContext(r.Context(), "update binding", "err", err, "id", id)
|
||||
http.Error(w, "update binding failed", http.StatusInternalServerError)
|
||||
}
|
||||
return
|
||||
}
|
||||
updated, err := a.bindings.GetBinding(r.Context(), id)
|
||||
if err != nil || updated == nil {
|
||||
a.log.ErrorContext(r.Context(), "get binding after update", "err", err, "id", id)
|
||||
http.Error(w, "update binding failed", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
writeJSON(w, updated)
|
||||
}
|
||||
|
||||
func (a *bindingsAPI) handleBindingDelete(w http.ResponseWriter, r *http.Request) {
|
||||
if !a.authorizeTaskMutation(w, r) {
|
||||
return
|
||||
}
|
||||
id := r.PathValue("id")
|
||||
if id == "" {
|
||||
http.Error(w, "invalid binding id", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if err := a.bindings.DeleteBinding(r.Context(), id); err != nil {
|
||||
if errors.Is(err, storecontract.ErrBindingNotFound) {
|
||||
http.Error(w, "binding not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
a.log.ErrorContext(r.Context(), "delete binding", "err", err, "id", id)
|
||||
http.Error(w, "delete binding failed", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// handleBindingTransition serves one binding lifecycle command (approve,
|
||||
// pause, resume) and answers the binding as it now stands.
|
||||
func (a *bindingsAPI) handleBindingTransition(verb string, apply func(storecontract.BindingStore, context.Context, string) error) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
if !a.authorizeTaskMutation(w, r) {
|
||||
return
|
||||
}
|
||||
id := r.PathValue("id")
|
||||
if id == "" {
|
||||
http.Error(w, "invalid binding id", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if err := apply(a.bindings, r.Context(), id); err != nil {
|
||||
switch {
|
||||
case errors.Is(err, storecontract.ErrBindingNotFound):
|
||||
http.Error(w, "binding not found", http.StatusNotFound)
|
||||
case errors.Is(err, storecontract.ErrBindingTransition):
|
||||
http.Error(w, "binding cannot "+verb+" from its current state", http.StatusConflict)
|
||||
default:
|
||||
a.log.ErrorContext(r.Context(), verb+" binding", "err", err, "id", id)
|
||||
http.Error(w, verb+" binding failed", http.StatusInternalServerError)
|
||||
}
|
||||
return
|
||||
}
|
||||
updated, err := a.bindings.GetBinding(r.Context(), id)
|
||||
if err != nil || updated == nil {
|
||||
a.log.ErrorContext(r.Context(), "get binding after "+verb, "err", err, "id", id)
|
||||
http.Error(w, verb+" binding failed", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
writeJSON(w, updated)
|
||||
}
|
||||
}
|
||||
|
||||
// checkedBinding builds the binding a create or update request describes and
|
||||
// refuses it, having written the error, unless it is well-formed, its mapping
|
||||
// exists, its filter compiles against the mapping's parameters, and its inputs
|
||||
// and repository satisfy the workflow it targets.
|
||||
func (a *bindingsAPI) checkedBinding(w http.ResponseWriter, r *http.Request, id string, req bindingRequest) (binding.Binding, bool) {
|
||||
b := binding.Binding{
|
||||
ID: id,
|
||||
Name: req.Name,
|
||||
Matcher: req.Matcher,
|
||||
MappingID: req.MappingID,
|
||||
Filter: req.Filter,
|
||||
Workflow: req.Workflow,
|
||||
Owner: req.Owner,
|
||||
Repo: req.Repo,
|
||||
RepoParam: req.RepoParam,
|
||||
Inputs: req.Inputs,
|
||||
Status: binding.StatusPendingApproval,
|
||||
}
|
||||
if err := b.Validate(); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return binding.Binding{}, false
|
||||
}
|
||||
entry, found, err := a.workflowEntry(r.Context(), req.Workflow)
|
||||
if err != nil {
|
||||
http.Error(w, "workflow definitions unavailable", http.StatusServiceUnavailable)
|
||||
return binding.Binding{}, false
|
||||
}
|
||||
if !found {
|
||||
http.Error(w, "binding: workflow not found: "+req.Workflow, http.StatusBadRequest)
|
||||
return binding.Binding{}, false
|
||||
}
|
||||
enabled, err := a.bindingWorkflowEnabled(r.Context(), id, req.Workflow)
|
||||
if err != nil {
|
||||
http.Error(w, "workflow enablement unavailable", http.StatusServiceUnavailable)
|
||||
return binding.Binding{}, false
|
||||
}
|
||||
if !enabled {
|
||||
http.Error(w, "binding: workflow is disabled: "+req.Workflow, http.StatusConflict)
|
||||
return binding.Binding{}, false
|
||||
}
|
||||
iface, err := task.ParseWorkflowInterface(entry.YAML)
|
||||
if err != nil {
|
||||
http.Error(w, "binding: workflow "+req.Workflow+": "+err.Error(), http.StatusBadRequest)
|
||||
return binding.Binding{}, false
|
||||
}
|
||||
if a.mappings == nil {
|
||||
http.Error(w, "mappings not configured", http.StatusServiceUnavailable)
|
||||
return binding.Binding{}, false
|
||||
}
|
||||
m, err := a.mappings.GetMapping(r.Context(), b.MappingID)
|
||||
if err != nil {
|
||||
a.log.ErrorContext(r.Context(), "get mapping for binding", "err", err, "mapping", b.MappingID)
|
||||
http.Error(w, "get mapping failed", http.StatusInternalServerError)
|
||||
return binding.Binding{}, false
|
||||
}
|
||||
if m == nil {
|
||||
http.Error(w, "binding: mapping not found: "+b.MappingID, http.StatusBadRequest)
|
||||
return binding.Binding{}, false
|
||||
}
|
||||
if _, err := binding.CompileFilter(b.Filter, m.Fields); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return binding.Binding{}, false
|
||||
}
|
||||
if err := b.CheckWorkflow(iface, m.Fields); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return binding.Binding{}, false
|
||||
}
|
||||
return b, true
|
||||
}
|
||||
|
||||
// bindingWorkflowEnabled reports whether the org owning binding id (the
|
||||
// default org for a binding not yet created) has workflow enabled.
|
||||
func (a *bindingsAPI) bindingWorkflowEnabled(ctx context.Context, id, workflow string) (bool, error) {
|
||||
owner := org.DefaultOrgID
|
||||
if id != "" {
|
||||
existing, err := a.bindings.GetBinding(ctx, id)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if existing != nil {
|
||||
owner = existing.OrgID
|
||||
}
|
||||
}
|
||||
enablement, _, err := a.workflowEnablement(ctx)
|
||||
return enablement.Enabled(owner, workflow), err
|
||||
}
|
||||
@@ -136,20 +136,49 @@ type chatToolView struct {
|
||||
TextOffset int `json:"text_offset,omitempty"`
|
||||
}
|
||||
|
||||
func (s *Server) chatReady(w http.ResponseWriter) (*ChatService, bool) {
|
||||
if s.Chat == nil || s.Chat.Contract == nil {
|
||||
// chatAPI owns the /api/chat routes and the state they share: questions
|
||||
// waiting for the browser's answer and files a turn offered for download.
|
||||
type chatAPI struct {
|
||||
chat *ChatService
|
||||
updateReportPath string
|
||||
configSource func() ConfigViewSource
|
||||
|
||||
asks chatAsks
|
||||
files chatFiles
|
||||
}
|
||||
|
||||
func newChatAPI(s *Server) *chatAPI {
|
||||
return &chatAPI{chat: s.Chat, updateReportPath: s.UpdateReportPath, configSource: s.configSource}
|
||||
}
|
||||
|
||||
func (a *chatAPI) register(mux *http.ServeMux) {
|
||||
mux.HandleFunc("GET /api/chat/sessions", a.handleChatSessions)
|
||||
mux.HandleFunc("GET /api/chat/sessions/{id}/messages", a.handleChatMessages)
|
||||
mux.HandleFunc("GET /api/chat/sessions/{id}/turns", a.handleChatTurns)
|
||||
mux.HandleFunc("POST /api/chat/message", a.handleChatMessage)
|
||||
mux.HandleFunc("POST /api/chat/stream", a.handleChatStream)
|
||||
mux.HandleFunc("POST /api/chat/cancel", a.handleChatCancel)
|
||||
mux.HandleFunc("POST /api/chat/answer", a.handleChatAnswer)
|
||||
mux.HandleFunc("GET /api/chat/file/{token}", a.handleChatFile)
|
||||
mux.HandleFunc("GET /api/chat/update", instanceOnly(a.handleChatUpdate))
|
||||
mux.HandleFunc("POST /api/chat/update/defer", instanceOnly(a.handleChatUpdateDefer))
|
||||
mux.HandleFunc("POST /api/chat/update/install", instanceOnly(a.handleChatUpdateInstall))
|
||||
}
|
||||
|
||||
func (a *chatAPI) chatReady(w http.ResponseWriter) (*ChatService, bool) {
|
||||
if a.chat == nil || a.chat.Contract == nil {
|
||||
http.Error(w, "chat is not configured", http.StatusNotImplemented)
|
||||
return nil, false
|
||||
}
|
||||
return s.Chat, true
|
||||
return a.chat, true
|
||||
}
|
||||
|
||||
func chatUpdateServiceConfigured(updates ChatUpdateService) bool {
|
||||
return !lifecycle.IsNil(updates)
|
||||
}
|
||||
|
||||
func (s *Server) handleChatSessions(w http.ResponseWriter, r *http.Request) {
|
||||
chat, ok := s.chatReady(w)
|
||||
func (a *chatAPI) handleChatSessions(w http.ResponseWriter, r *http.Request) {
|
||||
chat, ok := a.chatReady(w)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
@@ -160,7 +189,7 @@ func (s *Server) handleChatSessions(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
out := make([]messaging.SessionContext, 0, len(snapshot.Sessions))
|
||||
for _, session := range snapshot.Sessions {
|
||||
if s.ownsChatSession(r.Context(), session) {
|
||||
if a.ownsChatSession(r.Context(), session) {
|
||||
out = append(out, session)
|
||||
}
|
||||
}
|
||||
@@ -181,8 +210,8 @@ func chatCommandSpecs(chat *ChatService) []messaging.CommandSpec {
|
||||
return specs
|
||||
}
|
||||
|
||||
func (s *Server) handleChatMessages(w http.ResponseWriter, r *http.Request) {
|
||||
chat, ok := s.chatReady(w)
|
||||
func (a *chatAPI) handleChatMessages(w http.ResponseWriter, r *http.Request) {
|
||||
chat, ok := a.chatReady(w)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
@@ -192,7 +221,7 @@ func (s *Server) handleChatMessages(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
if !found || !s.ownsChatSession(r.Context(), session) {
|
||||
if !found || !a.ownsChatSession(r.Context(), session) {
|
||||
http.Error(w, "session not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
@@ -212,8 +241,8 @@ func (s *Server) handleChatMessages(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, views)
|
||||
}
|
||||
|
||||
func (s *Server) handleChatTurns(w http.ResponseWriter, r *http.Request) {
|
||||
chat, ok := s.chatReady(w)
|
||||
func (a *chatAPI) handleChatTurns(w http.ResponseWriter, r *http.Request) {
|
||||
chat, ok := a.chatReady(w)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
@@ -223,7 +252,7 @@ func (s *Server) handleChatTurns(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
if !found || !s.ownsChatSession(r.Context(), session) {
|
||||
if !found || !a.ownsChatSession(r.Context(), session) {
|
||||
http.Error(w, "session not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
@@ -250,7 +279,7 @@ func (s *Server) handleChatTurns(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, views)
|
||||
}
|
||||
|
||||
func (s *Server) decodeChatMessage(w http.ResponseWriter, r *http.Request) (messaging.Inbound, bool) {
|
||||
func (a *chatAPI) decodeChatMessage(w http.ResponseWriter, r *http.Request) (messaging.Inbound, bool) {
|
||||
var req chatMessageRequest
|
||||
// Base64 makes a clip a third larger than its bytes.
|
||||
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxVoiceBytes*3/2)).Decode(&req); err != nil {
|
||||
@@ -300,12 +329,12 @@ func (s *Server) decodeChatMessage(w http.ResponseWriter, r *http.Request) (mess
|
||||
}, true
|
||||
}
|
||||
|
||||
func (s *Server) handleChatMessage(w http.ResponseWriter, r *http.Request) {
|
||||
chat, ok := s.chatReady(w)
|
||||
func (a *chatAPI) handleChatMessage(w http.ResponseWriter, r *http.Request) {
|
||||
chat, ok := a.chatReady(w)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
msg, ok := s.decodeChatMessage(w, r)
|
||||
msg, ok := a.decodeChatMessage(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
@@ -398,20 +427,20 @@ func (s chatStreamSink) Media(event messaging.MediaEvent) {
|
||||
|
||||
// chatShowToolCalls reports config.ChatConfig.ShowToolCalls, false when no
|
||||
// config is available.
|
||||
func (s *Server) chatShowToolCalls(ctx context.Context) bool {
|
||||
view, found, err := s.configSource()(ctx)
|
||||
func (a *chatAPI) chatShowToolCalls(ctx context.Context) bool {
|
||||
view, found, err := a.configSource()(ctx)
|
||||
if err != nil || !found {
|
||||
return false
|
||||
}
|
||||
return view.Chat.ShowToolCalls
|
||||
}
|
||||
|
||||
func (s *Server) handleChatStream(w http.ResponseWriter, r *http.Request) {
|
||||
chat, ok := s.chatReady(w)
|
||||
func (a *chatAPI) handleChatStream(w http.ResponseWriter, r *http.Request) {
|
||||
chat, ok := a.chatReady(w)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
msg, ok := s.decodeChatMessage(w, r)
|
||||
msg, ok := a.decodeChatMessage(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
@@ -434,13 +463,13 @@ func (s *Server) handleChatStream(w http.ResponseWriter, r *http.Request) {
|
||||
_, _ = fmt.Fprintf(w, "data: %s\n\n", payload)
|
||||
flusher.Flush()
|
||||
}
|
||||
asker := dashboardAsker{asks: &s.chatAsks, write: func(frame chatStreamEvent) { writeChatEvent(frame, "") }}
|
||||
asker := dashboardAsker{asks: &a.asks, write: func(frame chatStreamEvent) { writeChatEvent(frame, "") }}
|
||||
events, err := chat.Contract.Stream(withDashboardAsks(r.Context(), asker), msg)
|
||||
if err != nil {
|
||||
writeChatEvent(chatStreamEvent{Type: "error", Text: err.Error()}, "")
|
||||
return
|
||||
}
|
||||
sink := chatStreamSink{showToolCalls: s.chatShowToolCalls(r.Context()), files: &s.chatFiles, owner: chatUser(r.Context())}
|
||||
sink := chatStreamSink{showToolCalls: a.chatShowToolCalls(r.Context()), files: &a.files, owner: chatUser(r.Context())}
|
||||
for event := range events {
|
||||
sink.write = func(frame chatStreamEvent) { writeChatEvent(frame, event.SessionID) }
|
||||
switch event.Kind {
|
||||
@@ -454,8 +483,8 @@ func (s *Server) handleChatStream(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) handleChatCancel(w http.ResponseWriter, r *http.Request) {
|
||||
chat, ok := s.chatReady(w)
|
||||
func (a *chatAPI) handleChatCancel(w http.ResponseWriter, r *http.Request) {
|
||||
chat, ok := a.chatReady(w)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
@@ -478,7 +507,7 @@ func (s *Server) handleChatCancel(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
if !found || !s.ownsChatSession(r.Context(), session) {
|
||||
if !found || !a.ownsChatSession(r.Context(), session) {
|
||||
http.Error(w, "session not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
@@ -500,8 +529,8 @@ func writeUpdateCheckError(w http.ResponseWriter, err error) {
|
||||
http.Error(w, err.Error(), http.StatusBadGateway)
|
||||
}
|
||||
|
||||
func (s *Server) handleChatUpdate(w http.ResponseWriter, r *http.Request) {
|
||||
chat, ok := s.chatReady(w)
|
||||
func (a *chatAPI) handleChatUpdate(w http.ResponseWriter, r *http.Request) {
|
||||
chat, ok := a.chatReady(w)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
@@ -533,8 +562,8 @@ func updateStateDir() string {
|
||||
return configuration.UpdateStateDir()
|
||||
}
|
||||
|
||||
func (s *Server) handleChatUpdateDefer(w http.ResponseWriter, r *http.Request) {
|
||||
chat, ok := s.chatReady(w)
|
||||
func (a *chatAPI) handleChatUpdateDefer(w http.ResponseWriter, r *http.Request) {
|
||||
chat, ok := a.chatReady(w)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
@@ -554,8 +583,8 @@ func (s *Server) handleChatUpdateDefer(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, map[string]bool{"ok": true})
|
||||
}
|
||||
|
||||
func (s *Server) handleChatUpdateInstall(w http.ResponseWriter, r *http.Request) {
|
||||
chat, ok := s.chatReady(w)
|
||||
func (a *chatAPI) handleChatUpdateInstall(w http.ResponseWriter, r *http.Request) {
|
||||
chat, ok := a.chatReady(w)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
@@ -592,7 +621,7 @@ func (s *Server) handleChatUpdateInstall(w http.ResponseWriter, r *http.Request)
|
||||
}()
|
||||
|
||||
progress := make([]string, 0, 4)
|
||||
meta := releaseupdate.InstallMeta{Channel: "webui", ReportPath: s.UpdateReportPath}
|
||||
meta := releaseupdate.InstallMeta{Channel: "webui", ReportPath: a.updateReportPath}
|
||||
result, err := chat.Updates.Install(r.Context(), fresh, meta, func(message string) { progress = append(progress, message) })
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadGateway)
|
||||
@@ -618,6 +647,6 @@ func chatUser(ctx context.Context) string {
|
||||
return ""
|
||||
}
|
||||
|
||||
func (s *Server) ownsChatSession(ctx context.Context, session messaging.SessionContext) bool {
|
||||
func (a *chatAPI) ownsChatSession(ctx context.Context, session messaging.SessionContext) bool {
|
||||
return session.Source.Platform == "web" && session.Source.ThreadID == chatUser(ctx)
|
||||
}
|
||||
@@ -189,13 +189,13 @@ type chatAnswerRequest struct {
|
||||
}
|
||||
|
||||
// handleChatAnswer delivers the operator's answer to the ask a turn waits on.
|
||||
func (s *Server) handleChatAnswer(w http.ResponseWriter, r *http.Request) {
|
||||
func (a *chatAPI) handleChatAnswer(w http.ResponseWriter, r *http.Request) {
|
||||
var req chatAnswerRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.ID == "" {
|
||||
http.Error(w, "id is required", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if !s.chatAsks.answer(req.ID, req.Answer, chatUser(r.Context())) {
|
||||
if !a.asks.answer(req.ID, req.Answer, chatUser(r.Context())) {
|
||||
http.Error(w, "that question is no longer waiting", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
@@ -72,8 +72,8 @@ func (c *chatFiles) lookup(token string) (chatFile, bool) {
|
||||
return f, true
|
||||
}
|
||||
|
||||
func (s *Server) handleChatFile(w http.ResponseWriter, r *http.Request) {
|
||||
f, ok := s.chatFiles.lookup(r.PathValue("token"))
|
||||
func (a *chatAPI) handleChatFile(w http.ResponseWriter, r *http.Request) {
|
||||
f, ok := a.files.lookup(r.PathValue("token"))
|
||||
if !ok || f.owner != chatUser(r.Context()) {
|
||||
http.Error(w, "that file is no longer available", http.StatusNotFound)
|
||||
return
|
||||
@@ -19,10 +19,10 @@ func TestChatFileDownload(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
now := time.Now()
|
||||
srv := &Server{}
|
||||
srv.chatFiles.now = func() time.Time { return now }
|
||||
token := srv.chatFiles.offer(path, "")
|
||||
private := srv.chatFiles.offerFor(path, "", "alice")
|
||||
srv := newChatAPI(&Server{})
|
||||
srv.files.now = func() time.Time { return now }
|
||||
token := srv.files.offer(path, "")
|
||||
private := srv.files.offerFor(path, "", "alice")
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
@@ -41,7 +41,7 @@ func TestChatFileDownload(t *testing.T) {
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
srv.chatFiles.now = func() time.Time { return now.Add(tt.after) }
|
||||
srv.files.now = func() time.Time { return now.Add(tt.after) }
|
||||
ctx := t.Context()
|
||||
if tt.user != "" {
|
||||
ctx = WithActingIdentity(ctx, identity.Identity{ID: identity.IdentityID(tt.user)})
|
||||
@@ -36,11 +36,11 @@ func (ownedChat) Cancel(context.Context, string) (messaging.ChatCancellation, er
|
||||
func TestWebChatOwnership(t *testing.T) {
|
||||
for _, route := range []struct {
|
||||
name, body string
|
||||
handler func(*Server, http.ResponseWriter, *http.Request)
|
||||
handler func(*chatAPI, http.ResponseWriter, *http.Request)
|
||||
}{
|
||||
{"messages", "", (*Server).handleChatMessages},
|
||||
{"turns", "", (*Server).handleChatTurns},
|
||||
{"cancel", `{"session_id":"private"}`, (*Server).handleChatCancel},
|
||||
{"messages", "", (*chatAPI).handleChatMessages},
|
||||
{"turns", "", (*chatAPI).handleChatTurns},
|
||||
{"cancel", `{"session_id":"private"}`, (*chatAPI).handleChatCancel},
|
||||
} {
|
||||
for _, user := range []string{"alice", "bob"} {
|
||||
t.Run(route.name+"/"+user, func(t *testing.T) {
|
||||
@@ -49,7 +49,7 @@ func TestWebChatOwnership(t *testing.T) {
|
||||
req.SetPathValue("id", "private")
|
||||
rec := httptest.NewRecorder()
|
||||
srv := &Server{Chat: &ChatService{Contract: ownedChat{}}}
|
||||
route.handler(srv, rec, req)
|
||||
route.handler(newChatAPI(srv), rec, req)
|
||||
want := 200
|
||||
if user != "alice" {
|
||||
want = 404
|
||||
@@ -65,7 +65,7 @@ func TestWebChatOwnership(t *testing.T) {
|
||||
func TestWebChatSenderCannotBeSuppliedByBrowser(t *testing.T) {
|
||||
ctx := WithActingIdentity(t.Context(), identity.Identity{ID: "alice"})
|
||||
req := httptest.NewRequestWithContext(ctx, "POST", "https://archie.example/api/chat/message", strings.NewReader(`{"channel_id":"browser-channel","text":"hello","sender_id":"bob","thread_id":"bob"}`))
|
||||
value, ok := (&Server{}).decodeChatMessage(httptest.NewRecorder(), req)
|
||||
value, ok := newChatAPI(&Server{}).decodeChatMessage(httptest.NewRecorder(), req)
|
||||
if !ok {
|
||||
t.Fatal("message refused")
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
@@ -46,12 +47,30 @@ type controlPlaneHistoryResponse struct {
|
||||
Revisions []controlPlaneRevision `json:"revisions"`
|
||||
}
|
||||
|
||||
func (s *Server) handleControlPlaneCatalog(w http.ResponseWriter, r *http.Request) {
|
||||
if s.ControlPlane == nil {
|
||||
// controlPlaneAPI owns the generic /api/control-plane resource routes. A nil
|
||||
// client answers 503.
|
||||
type controlPlaneAPI struct {
|
||||
controlPlane controlpb.ControlPlaneServiceClient
|
||||
actorNames func(context.Context) func(string) string
|
||||
}
|
||||
|
||||
func newControlPlaneAPI(s *Server) *controlPlaneAPI {
|
||||
return &controlPlaneAPI{controlPlane: s.ControlPlane, actorNames: s.actorNames}
|
||||
}
|
||||
|
||||
func (a *controlPlaneAPI) register(mux *http.ServeMux) {
|
||||
mux.HandleFunc("GET /api/control-plane/catalog", a.handleControlPlaneCatalog)
|
||||
mux.HandleFunc("GET /api/control-plane/resources/{kind}", a.handleControlPlaneQuery)
|
||||
mux.HandleFunc("GET /api/control-plane/resources/{kind}/history", a.handleControlPlaneHistory)
|
||||
mux.HandleFunc("POST /api/control-plane/resources/{kind}/commands/{command}", a.handleControlPlaneCommand)
|
||||
}
|
||||
|
||||
func (a *controlPlaneAPI) handleControlPlaneCatalog(w http.ResponseWriter, r *http.Request) {
|
||||
if a.controlPlane == nil {
|
||||
http.Error(w, "control plane unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
response, err := s.ControlPlane.Catalog(r.Context(), &controlpb.CatalogRequest{})
|
||||
response, err := a.controlPlane.Catalog(r.Context(), &controlpb.CatalogRequest{})
|
||||
if err != nil {
|
||||
writeControlPlaneError(w, err)
|
||||
return
|
||||
@@ -59,12 +78,12 @@ func (s *Server) handleControlPlaneCatalog(w http.ResponseWriter, r *http.Reques
|
||||
writeJSON(w, response)
|
||||
}
|
||||
|
||||
func (s *Server) handleControlPlaneQuery(w http.ResponseWriter, r *http.Request) {
|
||||
if s.ControlPlane == nil {
|
||||
func (a *controlPlaneAPI) handleControlPlaneQuery(w http.ResponseWriter, r *http.Request) {
|
||||
if a.controlPlane == nil {
|
||||
http.Error(w, "control plane unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
response, err := s.ControlPlane.Query(r.Context(), &controlpb.QueryRequest{Kind: r.PathValue("kind")})
|
||||
response, err := a.controlPlane.Query(r.Context(), &controlpb.QueryRequest{Kind: r.PathValue("kind")})
|
||||
if err != nil {
|
||||
writeControlPlaneError(w, err)
|
||||
return
|
||||
@@ -72,18 +91,18 @@ func (s *Server) handleControlPlaneQuery(w http.ResponseWriter, r *http.Request)
|
||||
writeJSON(w, controlPlaneResourceResponse{Resource: controlPlaneResourceView(response.Resource)})
|
||||
}
|
||||
|
||||
func (s *Server) handleControlPlaneHistory(w http.ResponseWriter, r *http.Request) {
|
||||
if s.ControlPlane == nil {
|
||||
func (a *controlPlaneAPI) handleControlPlaneHistory(w http.ResponseWriter, r *http.Request) {
|
||||
if a.controlPlane == nil {
|
||||
http.Error(w, "control plane unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
response, err := s.ControlPlane.History(r.Context(), &controlpb.HistoryRequest{Kind: r.PathValue("kind")})
|
||||
response, err := a.controlPlane.History(r.Context(), &controlpb.HistoryRequest{Kind: r.PathValue("kind")})
|
||||
if err != nil {
|
||||
writeControlPlaneError(w, err)
|
||||
return
|
||||
}
|
||||
revisions := make([]controlPlaneRevision, 0, len(response.Revisions))
|
||||
actorName := s.actorNames(r.Context())
|
||||
actorName := a.actorNames(r.Context())
|
||||
for _, revision := range response.Revisions {
|
||||
// The value is real, not redacted: the dashboard stages a revision and
|
||||
// applies it as a replace, so a redacted value would restore the marker.
|
||||
@@ -100,8 +119,8 @@ func (s *Server) handleControlPlaneHistory(w http.ResponseWriter, r *http.Reques
|
||||
writeJSON(w, controlPlaneHistoryResponse{Revisions: revisions})
|
||||
}
|
||||
|
||||
func (s *Server) handleControlPlaneCommand(w http.ResponseWriter, r *http.Request) {
|
||||
if s.ControlPlane == nil {
|
||||
func (a *controlPlaneAPI) handleControlPlaneCommand(w http.ResponseWriter, r *http.Request) {
|
||||
if a.controlPlane == nil {
|
||||
http.Error(w, "control plane unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
@@ -115,7 +134,7 @@ func (s *Server) handleControlPlaneCommand(w http.ResponseWriter, r *http.Reques
|
||||
http.Error(w, "cannot create request ID", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
response, err := s.ControlPlane.Command(r.Context(), &controlpb.CommandRequest{
|
||||
response, err := a.controlPlane.Command(r.Context(), &controlpb.CommandRequest{
|
||||
Kind: r.PathValue("kind"), Command: r.PathValue("command"), ValueJson: request.Value,
|
||||
ExpectedVersion: request.ExpectedVersion, Actor: string(audit.ActorID),
|
||||
Source: audit.Source, RequestId: audit.RequestID,
|
||||
@@ -2,12 +2,39 @@ package webui
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/eventtype"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
)
|
||||
|
||||
// eventTypesAPI owns the /api/event-types routes. eventTypes and captures stay
|
||||
// optional: the list answers {"enabled": false} with no store, and proposals
|
||||
// are empty without captures, as before.
|
||||
type eventTypesAPI struct {
|
||||
eventTypes storecontract.EventTypeStore
|
||||
captures storecontract.CaptureStore
|
||||
log *slog.Logger
|
||||
authorize func(http.ResponseWriter, *http.Request) bool
|
||||
}
|
||||
|
||||
func newEventTypesAPI(s *Server) *eventTypesAPI {
|
||||
return &eventTypesAPI{
|
||||
eventTypes: s.EventTypes,
|
||||
captures: s.Captures,
|
||||
log: s.Log,
|
||||
authorize: s.authorizeTaskMutation,
|
||||
}
|
||||
}
|
||||
|
||||
func (a *eventTypesAPI) register(mux *http.ServeMux) {
|
||||
mux.HandleFunc("GET /api/event-types", a.handleEventTypes)
|
||||
mux.HandleFunc("POST /api/event-types", a.handleEventTypeCreate)
|
||||
mux.HandleFunc("PUT /api/event-types/{id}", a.handleEventTypeUpdate)
|
||||
mux.HandleFunc("DELETE /api/event-types/{id}", a.handleEventTypeDelete)
|
||||
}
|
||||
|
||||
// proposalScanLimit bounds how many recent captures are grouped into
|
||||
// proposals on one read.
|
||||
const proposalScanLimit = 500
|
||||
@@ -37,22 +64,22 @@ type eventTypeUpdate struct {
|
||||
|
||||
// handleEventTypes lists the named event types and the proposals grouped from
|
||||
// recent captures that were unidentified on arrival and still match no type.
|
||||
func (s *Server) handleEventTypes(w http.ResponseWriter, r *http.Request) {
|
||||
if s.EventTypes == nil {
|
||||
func (a *eventTypesAPI) handleEventTypes(w http.ResponseWriter, r *http.Request) {
|
||||
if a.eventTypes == nil {
|
||||
writeJSON(w, map[string]any{"enabled": false, "event_types": []any{}, "proposals": []any{}})
|
||||
return
|
||||
}
|
||||
types, err := s.EventTypes.ListEventTypes(r.Context())
|
||||
types, err := a.eventTypes.ListEventTypes(r.Context())
|
||||
if err != nil {
|
||||
s.Log.ErrorContext(r.Context(), "list event types", "err", err)
|
||||
a.log.ErrorContext(r.Context(), "list event types", "err", err)
|
||||
http.Error(w, "list event types failed", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
proposals := []eventtype.Proposal{}
|
||||
if s.Captures != nil {
|
||||
captures, err := s.Captures.ListCaptures(r.Context(), proposalScanLimit)
|
||||
if a.captures != nil {
|
||||
captures, err := a.captures.ListCaptures(r.Context(), proposalScanLimit)
|
||||
if err != nil {
|
||||
s.Log.ErrorContext(r.Context(), "list captures for proposals", "err", err)
|
||||
a.log.ErrorContext(r.Context(), "list captures for proposals", "err", err)
|
||||
http.Error(w, "list captures failed", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
@@ -86,11 +113,11 @@ func unmatchedCaptures(types []eventtype.EventType, captures []storecontract.Cap
|
||||
return out
|
||||
}
|
||||
|
||||
func (s *Server) handleEventTypeCreate(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.authorizeTaskMutation(w, r) {
|
||||
func (a *eventTypesAPI) handleEventTypeCreate(w http.ResponseWriter, r *http.Request) {
|
||||
if !a.authorize(w, r) {
|
||||
return
|
||||
}
|
||||
if s.EventTypes == nil {
|
||||
if a.eventTypes == nil {
|
||||
http.Error(w, "event types not configured", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
@@ -105,9 +132,9 @@ func (s *Server) handleEventTypeCreate(w http.ResponseWriter, r *http.Request) {
|
||||
if req.Rule != nil {
|
||||
t.Rule = *req.Rule
|
||||
}
|
||||
id, err := s.EventTypes.InsertEventType(r.Context(), t)
|
||||
id, err := a.eventTypes.InsertEventType(r.Context(), t)
|
||||
if err != nil {
|
||||
s.writeEventTypeError(w, "create", err)
|
||||
a.writeEventTypeError(w, "create", err)
|
||||
return
|
||||
}
|
||||
t.ID = id
|
||||
@@ -115,11 +142,11 @@ func (s *Server) handleEventTypeCreate(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, t)
|
||||
}
|
||||
|
||||
func (s *Server) handleEventTypeUpdate(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.authorizeTaskMutation(w, r) {
|
||||
func (a *eventTypesAPI) handleEventTypeUpdate(w http.ResponseWriter, r *http.Request) {
|
||||
if !a.authorize(w, r) {
|
||||
return
|
||||
}
|
||||
if s.EventTypes == nil {
|
||||
if a.eventTypes == nil {
|
||||
http.Error(w, "event types not configured", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
@@ -129,29 +156,29 @@ func (s *Server) handleEventTypeUpdate(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
// Source is not editable: the store validates against the stored one.
|
||||
t := eventtype.EventType{ID: r.PathValue("id"), Name: req.Name, Rule: req.Rule}
|
||||
if err := s.EventTypes.UpdateEventType(r.Context(), t); err != nil {
|
||||
s.writeEventTypeError(w, "update", err)
|
||||
if err := a.eventTypes.UpdateEventType(r.Context(), t); err != nil {
|
||||
a.writeEventTypeError(w, "update", err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, map[string]string{"id": t.ID})
|
||||
}
|
||||
|
||||
func (s *Server) handleEventTypeDelete(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.authorizeTaskMutation(w, r) {
|
||||
func (a *eventTypesAPI) handleEventTypeDelete(w http.ResponseWriter, r *http.Request) {
|
||||
if !a.authorize(w, r) {
|
||||
return
|
||||
}
|
||||
if s.EventTypes == nil {
|
||||
if a.eventTypes == nil {
|
||||
http.Error(w, "event types not configured", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
if err := s.EventTypes.DeleteEventType(r.Context(), r.PathValue("id")); err != nil {
|
||||
s.writeEventTypeError(w, "delete", err)
|
||||
if err := a.eventTypes.DeleteEventType(r.Context(), r.PathValue("id")); err != nil {
|
||||
a.writeEventTypeError(w, "delete", err)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (s *Server) writeEventTypeError(w http.ResponseWriter, action string, err error) {
|
||||
func (a *eventTypesAPI) writeEventTypeError(w http.ResponseWriter, action string, err error) {
|
||||
switch {
|
||||
case errors.Is(err, eventtype.ErrOverlap):
|
||||
http.Error(w, "this rule can match events another type on the source already matches", http.StatusConflict)
|
||||
@@ -160,7 +187,7 @@ func (s *Server) writeEventTypeError(w http.ResponseWriter, action string, err e
|
||||
case errors.Is(err, storecontract.ErrEventTypeNotFound):
|
||||
http.Error(w, "event type not found", http.StatusNotFound)
|
||||
default:
|
||||
s.Log.Error(action+" event type", "err", err)
|
||||
a.log.Error(action+" event type", "err", err)
|
||||
http.Error(w, action+" event type failed", http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strings"
|
||||
@@ -13,6 +14,32 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/controlplanerpc"
|
||||
)
|
||||
|
||||
// extensionsAPI owns the /api/extensions routes. Handlers answer 503 until
|
||||
// both the package surface and the control plane are wired.
|
||||
type extensionsAPI struct {
|
||||
packages storepkg.Installations
|
||||
controlPlane controlpb.ControlPlaneServiceClient
|
||||
log *slog.Logger
|
||||
}
|
||||
|
||||
func newExtensionsAPI(s *Server) *extensionsAPI {
|
||||
return &extensionsAPI{packages: s.Packages, controlPlane: s.ControlPlane, log: s.Log}
|
||||
}
|
||||
|
||||
func (a *extensionsAPI) register(mux *http.ServeMux) {
|
||||
mux.HandleFunc("GET /api/extensions", a.handleExtensions)
|
||||
mux.HandleFunc("POST /api/extensions", a.handleExtensionInstall)
|
||||
mux.HandleFunc("GET /api/extensions/catalogue", a.handleCatalogue)
|
||||
mux.HandleFunc("POST /api/extensions/catalogue/{name}/install", a.handleCatalogueInstall)
|
||||
mux.HandleFunc("POST /api/extensions/{name}/accept", a.handleExtensionAccept)
|
||||
mux.HandleFunc("POST /api/extensions/{name}/update", a.handleExtensionUpdate)
|
||||
mux.HandleFunc("POST /api/extensions/{name}/approve-update", a.handleExtensionApproveUpdate)
|
||||
mux.HandleFunc("POST /api/extensions/{name}/rollback", a.handleExtensionRollback)
|
||||
mux.HandleFunc("PUT /api/extensions/{name}/update-policy", a.handleExtensionUpdatePolicy)
|
||||
mux.HandleFunc("PUT /api/extensions/{name}/enabled", a.handleExtensionEnabled)
|
||||
mux.HandleFunc("DELETE /api/extensions/{name}", a.handleExtensionRemove)
|
||||
}
|
||||
|
||||
type authorityView struct {
|
||||
CredentialServices []string `json:"credential_services"`
|
||||
EgressHosts []string `json:"egress_hosts"`
|
||||
@@ -107,9 +134,9 @@ func extensionView(p storepkg.Installed, enabled bool) ExtensionView {
|
||||
|
||||
// extensionSettings reads the extension-settings resource and the version a
|
||||
// replacement must name.
|
||||
func (s *Server) extensionSettings(ctx context.Context) (controlplanerpc.ExtensionSettings, int64, error) {
|
||||
func (a *extensionsAPI) extensionSettings(ctx context.Context) (controlplanerpc.ExtensionSettings, int64, error) {
|
||||
var doc controlplanerpc.ExtensionSettings
|
||||
response, err := s.ControlPlane.Query(ctx, &controlpb.QueryRequest{Kind: controlplanerpc.ExtensionSettingsKind})
|
||||
response, err := a.controlPlane.Query(ctx, &controlpb.QueryRequest{Kind: controlplanerpc.ExtensionSettingsKind})
|
||||
if err != nil {
|
||||
return doc, 0, err
|
||||
}
|
||||
@@ -123,7 +150,7 @@ func (s *Server) extensionSettings(ctx context.Context) (controlplanerpc.Extensi
|
||||
}
|
||||
|
||||
// putExtensionSettings replaces the extension-settings resource at version.
|
||||
func (s *Server) putExtensionSettings(ctx context.Context, doc controlplanerpc.ExtensionSettings, version int64) error {
|
||||
func (a *extensionsAPI) putExtensionSettings(ctx context.Context, doc controlplanerpc.ExtensionSettings, version int64) error {
|
||||
value, err := json.Marshal(doc)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -132,7 +159,7 @@ func (s *Server) putExtensionSettings(ctx context.Context, doc controlplanerpc.E
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = s.ControlPlane.Command(ctx, &controlpb.CommandRequest{
|
||||
_, err = a.controlPlane.Command(ctx, &controlpb.CommandRequest{
|
||||
Kind: controlplanerpc.ExtensionSettingsKind, Command: "replace", ValueJson: value,
|
||||
ExpectedVersion: version, Actor: string(audit.ActorID), Source: audit.Source, RequestId: audit.RequestID,
|
||||
})
|
||||
@@ -161,8 +188,8 @@ func withExtension(doc controlplanerpc.ExtensionSettings, name string, enabled *
|
||||
return next
|
||||
}
|
||||
|
||||
func (s *Server) extensionsReady(w http.ResponseWriter) bool {
|
||||
if s.Packages == nil || s.ControlPlane == nil {
|
||||
func (a *extensionsAPI) extensionsReady(w http.ResponseWriter) bool {
|
||||
if a.packages == nil || a.controlPlane == nil {
|
||||
http.Error(w, "extensions unavailable", http.StatusServiceUnavailable)
|
||||
return false
|
||||
}
|
||||
@@ -186,16 +213,16 @@ func writePackageError(w http.ResponseWriter, err error) {
|
||||
|
||||
// handleExtensions lists the installed packages with their authority and
|
||||
// enabled state.
|
||||
func (s *Server) handleExtensions(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.extensionsReady(w) {
|
||||
func (a *extensionsAPI) handleExtensions(w http.ResponseWriter, r *http.Request) {
|
||||
if !a.extensionsReady(w) {
|
||||
return
|
||||
}
|
||||
installed, err := s.Packages.ListInstalled(r.Context())
|
||||
installed, err := a.packages.ListInstalled(r.Context())
|
||||
if err != nil {
|
||||
writePackageError(w, err)
|
||||
return
|
||||
}
|
||||
doc, _, err := s.extensionSettings(r.Context())
|
||||
doc, _, err := a.extensionSettings(r.Context())
|
||||
if err != nil {
|
||||
writeControlPlaneError(w, err)
|
||||
return
|
||||
@@ -219,15 +246,15 @@ type installExtensionRequest struct {
|
||||
|
||||
// handleExtensionInstall installs a digest-pinned package. It does not enable
|
||||
// it and does not accept its authority: both are separate operator actions.
|
||||
func (s *Server) handleExtensionInstall(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.extensionsReady(w) {
|
||||
func (a *extensionsAPI) handleExtensionInstall(w http.ResponseWriter, r *http.Request) {
|
||||
if !a.extensionsReady(w) {
|
||||
return
|
||||
}
|
||||
request, ok := decodeBody[installExtensionRequest](w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
p, err := s.Packages.InstallPackage(r.Context(),
|
||||
p, err := a.packages.InstallPackage(r.Context(),
|
||||
strings.TrimSpace(request.Name), strings.TrimSpace(request.Reference), strings.TrimSpace(request.Digest))
|
||||
if err != nil {
|
||||
writePackageError(w, err)
|
||||
@@ -238,17 +265,17 @@ func (s *Server) handleExtensionInstall(w http.ResponseWriter, r *http.Request)
|
||||
|
||||
// handleExtensionAccept records the operator's acceptance of exactly the
|
||||
// authority the package declares.
|
||||
func (s *Server) handleExtensionAccept(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.extensionsReady(w) {
|
||||
func (a *extensionsAPI) handleExtensionAccept(w http.ResponseWriter, r *http.Request) {
|
||||
if !a.extensionsReady(w) {
|
||||
return
|
||||
}
|
||||
name := r.PathValue("name")
|
||||
installed, err := s.Packages.GetInstalled(r.Context(), name)
|
||||
installed, err := a.packages.GetInstalled(r.Context(), name)
|
||||
if err != nil {
|
||||
writePackageError(w, err)
|
||||
return
|
||||
}
|
||||
p, err := s.Packages.AcceptPackageAuthority(r.Context(), name, installed.Descriptor.Authority)
|
||||
p, err := a.packages.AcceptPackageAuthority(r.Context(), name, installed.Descriptor.Authority)
|
||||
if err != nil {
|
||||
writePackageError(w, err)
|
||||
return
|
||||
@@ -258,20 +285,20 @@ func (s *Server) handleExtensionAccept(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
// handleExtensionUpdate moves a package to the catalogue's digest: an update
|
||||
// that adds no authority applies, one that does waits as pending.
|
||||
func (s *Server) handleExtensionUpdate(w http.ResponseWriter, r *http.Request) {
|
||||
s.packageTransition(w, r, s.Packages.UpdatePackage)
|
||||
func (a *extensionsAPI) handleExtensionUpdate(w http.ResponseWriter, r *http.Request) {
|
||||
a.packageTransition(w, r, a.packages.UpdatePackage)
|
||||
}
|
||||
|
||||
// handleExtensionApproveUpdate applies the pending update and accepts the
|
||||
// authority it declares.
|
||||
func (s *Server) handleExtensionApproveUpdate(w http.ResponseWriter, r *http.Request) {
|
||||
s.packageTransition(w, r, s.Packages.ApprovePackageUpdate)
|
||||
func (a *extensionsAPI) handleExtensionApproveUpdate(w http.ResponseWriter, r *http.Request) {
|
||||
a.packageTransition(w, r, a.packages.ApprovePackageUpdate)
|
||||
}
|
||||
|
||||
// handleExtensionRollback restores the previous digest and its accepted
|
||||
// authority.
|
||||
func (s *Server) handleExtensionRollback(w http.ResponseWriter, r *http.Request) {
|
||||
s.packageTransition(w, r, s.Packages.RollbackPackage)
|
||||
func (a *extensionsAPI) handleExtensionRollback(w http.ResponseWriter, r *http.Request) {
|
||||
a.packageTransition(w, r, a.packages.RollbackPackage)
|
||||
}
|
||||
|
||||
type updatePolicyRequest struct {
|
||||
@@ -280,15 +307,15 @@ type updatePolicyRequest struct {
|
||||
|
||||
// handleExtensionUpdatePolicy sets whether the State Store updates a package
|
||||
// on its own.
|
||||
func (s *Server) handleExtensionUpdatePolicy(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.extensionsReady(w) {
|
||||
func (a *extensionsAPI) handleExtensionUpdatePolicy(w http.ResponseWriter, r *http.Request) {
|
||||
if !a.extensionsReady(w) {
|
||||
return
|
||||
}
|
||||
request, ok := decodeBody[updatePolicyRequest](w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
p, err := s.Packages.SetPackageUpdatePolicy(r.Context(), r.PathValue("name"), request.Policy)
|
||||
p, err := a.packages.SetPackageUpdatePolicy(r.Context(), r.PathValue("name"), request.Policy)
|
||||
if err != nil {
|
||||
writePackageError(w, err)
|
||||
return
|
||||
@@ -296,8 +323,8 @@ func (s *Server) handleExtensionUpdatePolicy(w http.ResponseWriter, r *http.Requ
|
||||
writeJSON(w, extensionView(p, false))
|
||||
}
|
||||
|
||||
func (s *Server) packageTransition(w http.ResponseWriter, r *http.Request, do func(context.Context, string) (storepkg.Installed, error)) {
|
||||
if !s.extensionsReady(w) {
|
||||
func (a *extensionsAPI) packageTransition(w http.ResponseWriter, r *http.Request, do func(context.Context, string) (storepkg.Installed, error)) {
|
||||
if !a.extensionsReady(w) {
|
||||
return
|
||||
}
|
||||
p, err := do(r.Context(), r.PathValue("name"))
|
||||
@@ -313,8 +340,8 @@ type extensionEnabledRequest struct {
|
||||
}
|
||||
|
||||
// handleExtensionEnabled enables or disables an installed extension.
|
||||
func (s *Server) handleExtensionEnabled(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.extensionsReady(w) {
|
||||
func (a *extensionsAPI) handleExtensionEnabled(w http.ResponseWriter, r *http.Request) {
|
||||
if !a.extensionsReady(w) {
|
||||
return
|
||||
}
|
||||
request, ok := decodeBody[extensionEnabledRequest](w, r)
|
||||
@@ -322,16 +349,16 @@ func (s *Server) handleExtensionEnabled(w http.ResponseWriter, r *http.Request)
|
||||
return
|
||||
}
|
||||
name := r.PathValue("name")
|
||||
if _, err := s.Packages.GetInstalled(r.Context(), name); err != nil {
|
||||
if _, err := a.packages.GetInstalled(r.Context(), name); err != nil {
|
||||
writePackageError(w, err)
|
||||
return
|
||||
}
|
||||
doc, version, err := s.extensionSettings(r.Context())
|
||||
doc, version, err := a.extensionSettings(r.Context())
|
||||
if err != nil {
|
||||
writeControlPlaneError(w, err)
|
||||
return
|
||||
}
|
||||
if err := s.putExtensionSettings(r.Context(), withExtension(doc, name, &request.Enabled), version); err != nil {
|
||||
if err := a.putExtensionSettings(r.Context(), withExtension(doc, name, &request.Enabled), version); err != nil {
|
||||
writeControlPlaneError(w, err)
|
||||
return
|
||||
}
|
||||
@@ -340,18 +367,18 @@ func (s *Server) handleExtensionEnabled(w http.ResponseWriter, r *http.Request)
|
||||
|
||||
// handleExtensionRemove uninstalls an extension and drops its setting, so a
|
||||
// later reinstall does not start enabled.
|
||||
func (s *Server) handleExtensionRemove(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.extensionsReady(w) {
|
||||
func (a *extensionsAPI) handleExtensionRemove(w http.ResponseWriter, r *http.Request) {
|
||||
if !a.extensionsReady(w) {
|
||||
return
|
||||
}
|
||||
name := r.PathValue("name")
|
||||
if err := s.Packages.RemoveInstalled(r.Context(), name); err != nil {
|
||||
if err := a.packages.RemoveInstalled(r.Context(), name); err != nil {
|
||||
writePackageError(w, err)
|
||||
return
|
||||
}
|
||||
if doc, version, err := s.extensionSettings(r.Context()); err == nil {
|
||||
if err := s.putExtensionSettings(r.Context(), withExtension(doc, name, nil), version); err != nil {
|
||||
s.Log.WarnContext(r.Context(), "drop extension setting", "name", name, "err", err)
|
||||
if doc, version, err := a.extensionSettings(r.Context()); err == nil {
|
||||
if err := a.putExtensionSettings(r.Context(), withExtension(doc, name, nil), version); err != nil {
|
||||
a.log.WarnContext(r.Context(), "drop extension setting", "name", name, "err", err)
|
||||
}
|
||||
}
|
||||
writeJSON(w, map[string]any{"name": name, "removed": true})
|
||||
@@ -365,16 +392,16 @@ type catalogueView struct {
|
||||
}
|
||||
|
||||
// handleCatalogue lists the packages the verified catalogue offers.
|
||||
func (s *Server) handleCatalogue(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.extensionsReady(w) {
|
||||
func (a *extensionsAPI) handleCatalogue(w http.ResponseWriter, r *http.Request) {
|
||||
if !a.extensionsReady(w) {
|
||||
return
|
||||
}
|
||||
catalogue, err := s.Packages.ListCatalogue(r.Context())
|
||||
catalogue, err := a.packages.ListCatalogue(r.Context())
|
||||
if err != nil {
|
||||
http.Error(w, "catalogue unavailable: "+err.Error(), http.StatusBadGateway)
|
||||
return
|
||||
}
|
||||
installed, err := s.Packages.ListInstalled(r.Context())
|
||||
installed, err := a.packages.ListInstalled(r.Context())
|
||||
if err != nil {
|
||||
writePackageError(w, err)
|
||||
return
|
||||
@@ -392,11 +419,11 @@ func (s *Server) handleCatalogue(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
// handleCatalogueInstall installs one catalogue package by name, at the digest
|
||||
// the verified catalogue pins.
|
||||
func (s *Server) handleCatalogueInstall(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.extensionsReady(w) {
|
||||
func (a *extensionsAPI) handleCatalogueInstall(w http.ResponseWriter, r *http.Request) {
|
||||
if !a.extensionsReady(w) {
|
||||
return
|
||||
}
|
||||
p, err := s.Packages.InstallFromCatalogue(r.Context(), r.PathValue("name"))
|
||||
p, err := a.packages.InstallFromCatalogue(r.Context(), r.PathValue("name"))
|
||||
if err != nil {
|
||||
writePackageError(w, err)
|
||||
return
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"sort"
|
||||
@@ -93,36 +94,56 @@ type harnessView struct {
|
||||
Profiles []string `json:"profiles"`
|
||||
}
|
||||
|
||||
// harnessAPI owns the /api/harness routes. Each dependency is optional and a
|
||||
// handler answers 503 when the one it needs is absent.
|
||||
type harnessAPI struct {
|
||||
controlPlane controlpb.ControlPlaneServiceClient
|
||||
secrets storecontract.HarnessSecretStore
|
||||
terminal HarnessTerminal
|
||||
log *slog.Logger
|
||||
}
|
||||
|
||||
func newHarnessAPI(s *Server) *harnessAPI {
|
||||
return &harnessAPI{controlPlane: s.ControlPlane, secrets: s.HarnessSecrets, terminal: s.HarnessTerminal, log: s.Log}
|
||||
}
|
||||
|
||||
func (a *harnessAPI) logf(msg string, args ...any) { warnf(a.log, msg, args...) }
|
||||
|
||||
func (a *harnessAPI) register(mux *http.ServeMux) {
|
||||
mux.HandleFunc("GET /api/harness/bindings", a.handleHarnessBindings)
|
||||
mux.HandleFunc("GET /api/harness/terminal", a.handleHarnessTerminal)
|
||||
}
|
||||
|
||||
// handleHarnessBindings lists the org's credential bindings joined with
|
||||
// their captured OAuth state. It requires both contracts the join reads: an
|
||||
// unconfigured process answers 503 rather than rendering a page that claims
|
||||
// the org has no bindings, which it cannot know.
|
||||
func (s *Server) handleHarnessBindings(w http.ResponseWriter, r *http.Request) {
|
||||
if s.ControlPlane == nil || s.HarnessSecrets == nil {
|
||||
func (a *harnessAPI) handleHarnessBindings(w http.ResponseWriter, r *http.Request) {
|
||||
if a.controlPlane == nil || a.secrets == nil {
|
||||
http.Error(w, "harness bindings not configured", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
orgID := string(org.OrgFromContext(r.Context()))
|
||||
bindings, err := s.harnessBindings(r.Context(), orgID)
|
||||
bindings, err := a.harnessBindings(r.Context(), orgID)
|
||||
if err != nil {
|
||||
s.logf("list harness bindings", "err", err)
|
||||
a.logf("list harness bindings", "err", err)
|
||||
http.Error(w, "list harness bindings failed", http.StatusBadGateway)
|
||||
return
|
||||
}
|
||||
profiles, err := s.harnessProfiles(r.Context())
|
||||
profiles, err := a.harnessProfiles(r.Context())
|
||||
if err != nil {
|
||||
s.logf("list harness profiles", "err", err)
|
||||
a.logf("list harness profiles", "err", err)
|
||||
http.Error(w, "list harness bindings failed", http.StatusBadGateway)
|
||||
return
|
||||
}
|
||||
writeJSON(w, harnessView{Terminal: s.HarnessTerminal != nil, Bindings: bindings, Profiles: profiles})
|
||||
writeJSON(w, harnessView{Terminal: a.terminal != nil, Bindings: bindings, Profiles: profiles})
|
||||
}
|
||||
|
||||
// harnessBindings reads the credential-bindings document and each service's
|
||||
// captured token state. A service with no captured set is not an error: it
|
||||
// is exactly the state the setup terminal exists to change.
|
||||
func (s *Server) harnessBindings(ctx context.Context, orgID string) ([]harnessBindingView, error) {
|
||||
response, err := s.ControlPlane.Query(ctx, &controlpb.QueryRequest{Kind: harnessBindingsKind})
|
||||
func (a *harnessAPI) harnessBindings(ctx context.Context, orgID string) ([]harnessBindingView, error) {
|
||||
response, err := a.controlPlane.Query(ctx, &controlpb.QueryRequest{Kind: harnessBindingsKind})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -138,7 +159,7 @@ func (s *Server) harnessBindings(ctx context.Context, orgID string) ([]harnessBi
|
||||
continue
|
||||
}
|
||||
view := harnessBindingView{Service: doc.Service}
|
||||
secret, err := s.HarnessSecrets.GetHarnessSecret(ctx, orgID, doc.Service)
|
||||
secret, err := a.secrets.GetHarnessSecret(ctx, orgID, doc.Service)
|
||||
switch {
|
||||
case err == nil:
|
||||
view.Captured = true
|
||||
@@ -163,8 +184,8 @@ func (s *Server) harnessBindings(ctx context.Context, orgID string) ([]harnessBi
|
||||
|
||||
// harnessProfiles returns the agent profiles that name a Kit, sorted so the
|
||||
// page's list does not depend on Go's map iteration order.
|
||||
func (s *Server) harnessProfiles(ctx context.Context) ([]string, error) {
|
||||
response, err := s.ControlPlane.Query(ctx, &controlpb.QueryRequest{Kind: harnessProfilesKind})
|
||||
func (a *harnessAPI) harnessProfiles(ctx context.Context) ([]string, error) {
|
||||
response, err := a.controlPlane.Query(ctx, &controlpb.QueryRequest{Kind: harnessProfilesKind})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -188,8 +209,8 @@ func (s *Server) harnessProfiles(ctx context.Context) ([]string, error) {
|
||||
// a setup session opened for the named Kit profile. Opening the terminal is
|
||||
// the update action on the secret, decided by the authorizer before this
|
||||
// handler runs (authorize.go's route override).
|
||||
func (s *Server) handleHarnessTerminal(w http.ResponseWriter, r *http.Request) {
|
||||
if s.HarnessTerminal == nil {
|
||||
func (a *harnessAPI) handleHarnessTerminal(w http.ResponseWriter, r *http.Request) {
|
||||
if a.terminal == nil {
|
||||
http.Error(w, "setup terminal not configured", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
@@ -204,9 +225,9 @@ func (s *Server) handleHarnessTerminal(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
rows := terminalSize(r.URL.Query(), "rows", terminalDefaultRows)
|
||||
cols := terminalSize(r.URL.Query(), "cols", terminalDefaultCols)
|
||||
session, err := s.HarnessTerminal.Open(r.Context(), string(org.OrgFromContext(r.Context())), profile, rows, cols)
|
||||
session, err := a.terminal.Open(r.Context(), string(org.OrgFromContext(r.Context())), profile, rows, cols)
|
||||
if err != nil {
|
||||
s.logf("open setup terminal", "err", err, "profile", profile)
|
||||
a.logf("open setup terminal", "err", err, "profile", profile)
|
||||
http.Error(w, "setup terminal failed", http.StatusBadGateway)
|
||||
return
|
||||
}
|
||||
@@ -19,6 +19,27 @@ import (
|
||||
// route needs: binding a token to a NAMED identity. The remote client's
|
||||
// caller-scoped PersonalTokens view cannot express that, so the store fronts
|
||||
// it as its own RPC and the Client carries it under this name.
|
||||
// identitiesAPI owns the identity routes and the signed-in person's API
|
||||
// tokens. Either store may be nil; its routes then answer Unavailable.
|
||||
type identitiesAPI struct {
|
||||
identities identity.Repository
|
||||
tokens identity.PersonalTokens
|
||||
}
|
||||
|
||||
func newIdentitiesAPI(s *Server) *identitiesAPI {
|
||||
return &identitiesAPI{identities: s.Identities, tokens: s.PersonalTokens}
|
||||
}
|
||||
|
||||
func (a *identitiesAPI) register(mux *http.ServeMux) {
|
||||
mux.HandleFunc("GET /api/identities", instanceOnly(a.handleIdentitiesList))
|
||||
mux.HandleFunc("POST /api/identities", instanceOnly(a.handleIdentityCreate))
|
||||
mux.HandleFunc("POST /api/identities/{id}/{command}", instanceOnly(a.handleIdentityCommand))
|
||||
mux.HandleFunc("POST /api/identities/{id}/tokens", instanceOnly(a.handleIdentityTokenCreate))
|
||||
mux.HandleFunc("GET /api/tokens", a.handlePersonalTokensList)
|
||||
mux.HandleFunc("POST /api/tokens", a.handlePersonalTokenCreate)
|
||||
mux.HandleFunc("DELETE /api/tokens/{id}", a.handlePersonalTokenRevoke)
|
||||
}
|
||||
|
||||
type identityTokenBinder interface {
|
||||
BindPersonalToken(ctx context.Context, id identity.IdentityID, subject identity.Subject, name string, expiresAt *time.Time, audit identity.Audit) error
|
||||
}
|
||||
@@ -32,12 +53,12 @@ type identityRequest struct {
|
||||
ExpectedVersion int64 `json:"expected_version"`
|
||||
}
|
||||
|
||||
func (s *Server) handleIdentitiesList(w http.ResponseWriter, r *http.Request) {
|
||||
if s.Identities == nil {
|
||||
func (a *identitiesAPI) handleIdentitiesList(w http.ResponseWriter, r *http.Request) {
|
||||
if a.identities == nil {
|
||||
http.Error(w, "identity store unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
values, err := s.Identities.List(r.Context())
|
||||
values, err := a.identities.List(r.Context())
|
||||
if err != nil {
|
||||
writeIdentityError(w, err)
|
||||
return
|
||||
@@ -48,7 +69,7 @@ func (s *Server) handleIdentitiesList(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, map[string]any{"identities": values})
|
||||
}
|
||||
|
||||
func (s *Server) handleIdentityCreate(w http.ResponseWriter, r *http.Request) {
|
||||
func (a *identitiesAPI) handleIdentityCreate(w http.ResponseWriter, r *http.Request) {
|
||||
request, ok := decodeBody[identityRequest](w, r)
|
||||
if !ok {
|
||||
return
|
||||
@@ -65,7 +86,7 @@ func (s *Server) handleIdentityCreate(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
value, err := identity.New(id, request.Kind, request.DisplayName)
|
||||
if err == nil {
|
||||
value, err = s.Identities.Create(r.Context(), value, audit)
|
||||
value, err = a.identities.Create(r.Context(), value, audit)
|
||||
}
|
||||
if err != nil {
|
||||
writeIdentityError(w, err)
|
||||
@@ -75,7 +96,7 @@ func (s *Server) handleIdentityCreate(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, value)
|
||||
}
|
||||
|
||||
func (s *Server) handleIdentityCommand(w http.ResponseWriter, r *http.Request) {
|
||||
func (a *identitiesAPI) handleIdentityCommand(w http.ResponseWriter, r *http.Request) {
|
||||
request, ok := decodeBody[identityRequest](w, r)
|
||||
if !ok {
|
||||
return
|
||||
@@ -86,7 +107,7 @@ func (s *Server) handleIdentityCommand(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
command := identity.Command{Type: identity.CommandType(r.PathValue("command")), DisplayName: request.DisplayName}
|
||||
value, err := s.Identities.Apply(r.Context(), identity.IdentityID(r.PathValue("id")), request.ExpectedVersion, command, audit)
|
||||
value, err := a.identities.Apply(r.Context(), identity.IdentityID(r.PathValue("id")), request.ExpectedVersion, command, audit)
|
||||
if err != nil {
|
||||
writeIdentityError(w, err)
|
||||
return
|
||||
@@ -98,13 +119,13 @@ func (s *Server) handleIdentityCommand(w http.ResponseWriter, r *http.Request) {
|
||||
// is how a non-user identity gets its bearer credential: a person's token
|
||||
// comes from /api/tokens, a service account's from here. The raw token is
|
||||
// returned exactly once; the store keeps only its hash.
|
||||
func (s *Server) handleIdentityTokenCreate(w http.ResponseWriter, r *http.Request) {
|
||||
func (a *identitiesAPI) handleIdentityTokenCreate(w http.ResponseWriter, r *http.Request) {
|
||||
id := identity.IdentityID(r.PathValue("id"))
|
||||
if s.Identities == nil {
|
||||
if a.identities == nil {
|
||||
http.Error(w, "identity store unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
value, err := s.Identities.Get(r.Context(), id)
|
||||
value, err := a.identities.Get(r.Context(), id)
|
||||
if errors.Is(err, identity.ErrNotFound) {
|
||||
http.Error(w, "No such identity.", http.StatusBadRequest)
|
||||
return
|
||||
@@ -123,7 +144,7 @@ func (s *Server) handleIdentityTokenCreate(w http.ResponseWriter, r *http.Reques
|
||||
}
|
||||
// The store side of the PersonalTokens contract binds a token to a named
|
||||
// identity; the remote caller's view only ever names its own principal.
|
||||
binder, ok := s.PersonalTokens.(identityTokenBinder)
|
||||
binder, ok := a.tokens.(identityTokenBinder)
|
||||
if !ok {
|
||||
http.Error(w, "identity token binding unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
@@ -17,7 +17,20 @@ import (
|
||||
// LogSource reads one service's bounded recent log over its contract.
|
||||
type LogSource func(context.Context, logging.Query) (logging.Result, error)
|
||||
|
||||
func (s *Server) handleLogs(w http.ResponseWriter, r *http.Request) {
|
||||
// logsAPI owns GET /api/logs. With no sources it reads this process's own
|
||||
// feed; with neither it reports logs disabled.
|
||||
type logsAPI struct {
|
||||
sources map[string]LogSource
|
||||
feed *logging.Feed
|
||||
}
|
||||
|
||||
func newLogsAPI(s *Server) *logsAPI { return &logsAPI{sources: s.LogSources, feed: s.LogFeed} }
|
||||
|
||||
func (a *logsAPI) register(mux *http.ServeMux) {
|
||||
mux.HandleFunc("GET /api/logs", instanceOnly(a.handleLogs))
|
||||
}
|
||||
|
||||
func (a *logsAPI) handleLogs(w http.ResponseWriter, r *http.Request) {
|
||||
q := r.URL.Query()
|
||||
limit := logging.DefaultTailLines
|
||||
if raw := strings.TrimSpace(q.Get("limit")); raw != "" {
|
||||
@@ -30,9 +43,9 @@ func (s *Server) handleLogs(w http.ResponseWriter, r *http.Request) {
|
||||
limit = min(parsed, logging.MaxTailLines)
|
||||
}
|
||||
}
|
||||
sources := s.LogSources
|
||||
sources := a.sources
|
||||
if len(sources) == 0 {
|
||||
sources = map[string]LogSource{presence.UI: func(_ context.Context, q logging.Query) (logging.Result, error) { return s.LogFeed.Read(q) }}
|
||||
sources = map[string]LogSource{presence.UI: func(_ context.Context, q logging.Query) (logging.Result, error) { return a.feed.Read(q) }}
|
||||
}
|
||||
service := q.Get("service")
|
||||
owner := service
|
||||
@@ -55,7 +68,7 @@ func (s *Server) handleLogs(w http.ResponseWriter, r *http.Request) {
|
||||
entries = entries[len(entries)-limit:]
|
||||
truncated = true
|
||||
}
|
||||
writeJSON(w, map[string]any{"entries": entries, "components": components, "services": services, "errors": errors, "truncated": truncated, "disabled": len(s.LogSources) == 0 && s.LogFeed == nil})
|
||||
writeJSON(w, map[string]any{"entries": entries, "components": components, "services": services, "errors": errors, "truncated": truncated, "disabled": len(a.sources) == 0 && a.feed == nil})
|
||||
}
|
||||
|
||||
func readServiceLogs(ctx context.Context, sources map[string]LogSource, selected string, q logging.Query) ([]logging.Entry, map[string]string, bool) {
|
||||
@@ -3,6 +3,7 @@ package webui
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"slices"
|
||||
|
||||
@@ -10,6 +11,49 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
)
|
||||
|
||||
// mappingsAPI owns the /api/mappings routes. Constructed only when the
|
||||
// mapping store is configured; Server mounts a 503 stub otherwise. eventTypes
|
||||
// and captures stay optional inside (validateMapping and preview answer 503).
|
||||
type mappingsAPI struct {
|
||||
mappings storecontract.MappingStore
|
||||
eventTypes storecontract.EventTypeStore
|
||||
captures storecontract.CaptureStore
|
||||
captureMaxEvents int
|
||||
log *slog.Logger
|
||||
authorize func(http.ResponseWriter, *http.Request) bool
|
||||
}
|
||||
|
||||
func newMappingsAPI(s *Server) *mappingsAPI {
|
||||
return &mappingsAPI{
|
||||
mappings: s.Mappings,
|
||||
eventTypes: s.EventTypes,
|
||||
captures: s.Captures,
|
||||
captureMaxEvents: s.CaptureMaxEvents,
|
||||
log: s.Log,
|
||||
authorize: s.authorizeTaskMutation,
|
||||
}
|
||||
}
|
||||
|
||||
// mappingsRoutes lists the method+path patterns the mappings module owns, so
|
||||
// the 503 stub mounts exactly the same routes.
|
||||
var mappingsRoutes = []string{
|
||||
"GET /api/mappings",
|
||||
"POST /api/mappings",
|
||||
"GET /api/mappings/{id}",
|
||||
"PATCH /api/mappings/{id}",
|
||||
"DELETE /api/mappings/{id}",
|
||||
"POST /api/mappings/preview",
|
||||
}
|
||||
|
||||
func (a *mappingsAPI) register(mux *http.ServeMux) {
|
||||
mux.HandleFunc("GET /api/mappings", a.handleMappingsList)
|
||||
mux.HandleFunc("POST /api/mappings", a.handleMappingCreate)
|
||||
mux.HandleFunc("GET /api/mappings/{id}", a.handleMappingGet)
|
||||
mux.HandleFunc("PATCH /api/mappings/{id}", a.handleMappingUpdate)
|
||||
mux.HandleFunc("DELETE /api/mappings/{id}", a.handleMappingDelete)
|
||||
mux.HandleFunc("POST /api/mappings/preview", a.handleMappingPreview)
|
||||
}
|
||||
|
||||
// mappingRequest is the wire shape POST /api/mappings and
|
||||
// PATCH /api/mappings/{id} both accept. ID/CreatedAt/UpdatedAt are
|
||||
// server-assigned, never taken from the request body.
|
||||
@@ -22,18 +66,18 @@ type mappingRequest struct {
|
||||
|
||||
// validateMapping checks m is well-formed and fits its event type's schema.
|
||||
// It writes the refusal and returns false when it does not.
|
||||
func (s *Server) validateMapping(w http.ResponseWriter, r *http.Request, m mapping.Mapping) bool {
|
||||
func (a *mappingsAPI) validateMapping(w http.ResponseWriter, r *http.Request, m mapping.Mapping) bool {
|
||||
if err := m.Validate(); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return false
|
||||
}
|
||||
if s.EventTypes == nil {
|
||||
if a.eventTypes == nil {
|
||||
http.Error(w, "event types not configured", http.StatusServiceUnavailable)
|
||||
return false
|
||||
}
|
||||
types, err := s.EventTypes.ListEventTypes(r.Context())
|
||||
types, err := a.eventTypes.ListEventTypes(r.Context())
|
||||
if err != nil {
|
||||
s.Log.ErrorContext(r.Context(), "list event types", "err", err)
|
||||
a.log.ErrorContext(r.Context(), "list event types", "err", err)
|
||||
http.Error(w, "list event types failed", http.StatusInternalServerError)
|
||||
return false
|
||||
}
|
||||
@@ -50,14 +94,14 @@ func (s *Server) validateMapping(w http.ResponseWriter, r *http.Request, m mappi
|
||||
return false
|
||||
}
|
||||
|
||||
func (s *Server) handleMappingsList(w http.ResponseWriter, r *http.Request) {
|
||||
if s.Mappings == nil {
|
||||
func (a *mappingsAPI) handleMappingsList(w http.ResponseWriter, r *http.Request) {
|
||||
if a.mappings == nil {
|
||||
http.Error(w, "mappings not configured", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
mappings, err := s.Mappings.ListMappings(r.Context())
|
||||
mappings, err := a.mappings.ListMappings(r.Context())
|
||||
if err != nil {
|
||||
s.Log.ErrorContext(r.Context(), "list mappings", "err", err)
|
||||
a.log.ErrorContext(r.Context(), "list mappings", "err", err)
|
||||
http.Error(w, "list mappings failed", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
@@ -65,11 +109,11 @@ func (s *Server) handleMappingsList(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, map[string]any{"mappings": mappings})
|
||||
}
|
||||
|
||||
func (s *Server) handleMappingCreate(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.authorizeTaskMutation(w, r) {
|
||||
func (a *mappingsAPI) handleMappingCreate(w http.ResponseWriter, r *http.Request) {
|
||||
if !a.authorize(w, r) {
|
||||
return
|
||||
}
|
||||
if s.Mappings == nil {
|
||||
if a.mappings == nil {
|
||||
http.Error(w, "mappings not configured", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
@@ -78,18 +122,18 @@ func (s *Server) handleMappingCreate(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
m := mapping.Mapping{Name: req.Name, SourceHint: req.SourceHint, EventTypeID: req.EventTypeID, Fields: req.Fields}
|
||||
if !s.validateMapping(w, r, m) {
|
||||
if !a.validateMapping(w, r, m) {
|
||||
return
|
||||
}
|
||||
id, err := s.Mappings.InsertMapping(r.Context(), m)
|
||||
id, err := a.mappings.InsertMapping(r.Context(), m)
|
||||
if err != nil {
|
||||
s.Log.ErrorContext(r.Context(), "insert mapping", "err", err)
|
||||
a.log.ErrorContext(r.Context(), "insert mapping", "err", err)
|
||||
http.Error(w, "create mapping failed", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
created, err := s.Mappings.GetMapping(r.Context(), id)
|
||||
created, err := a.mappings.GetMapping(r.Context(), id)
|
||||
if err != nil || created == nil {
|
||||
s.Log.ErrorContext(r.Context(), "get mapping after insert", "err", err, "id", id)
|
||||
a.log.ErrorContext(r.Context(), "get mapping after insert", "err", err, "id", id)
|
||||
http.Error(w, "create mapping failed", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
@@ -97,8 +141,8 @@ func (s *Server) handleMappingCreate(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, created)
|
||||
}
|
||||
|
||||
func (s *Server) handleMappingGet(w http.ResponseWriter, r *http.Request) {
|
||||
if s.Mappings == nil {
|
||||
func (a *mappingsAPI) handleMappingGet(w http.ResponseWriter, r *http.Request) {
|
||||
if a.mappings == nil {
|
||||
http.Error(w, "mappings not configured", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
@@ -107,9 +151,9 @@ func (s *Server) handleMappingGet(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, "invalid mapping id", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
m, err := s.Mappings.GetMapping(r.Context(), id)
|
||||
m, err := a.mappings.GetMapping(r.Context(), id)
|
||||
if err != nil {
|
||||
s.Log.ErrorContext(r.Context(), "get mapping", "err", err, "id", id)
|
||||
a.log.ErrorContext(r.Context(), "get mapping", "err", err, "id", id)
|
||||
http.Error(w, "get mapping failed", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
@@ -120,11 +164,11 @@ func (s *Server) handleMappingGet(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, m)
|
||||
}
|
||||
|
||||
func (s *Server) handleMappingUpdate(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.authorizeTaskMutation(w, r) {
|
||||
func (a *mappingsAPI) handleMappingUpdate(w http.ResponseWriter, r *http.Request) {
|
||||
if !a.authorize(w, r) {
|
||||
return
|
||||
}
|
||||
if s.Mappings == nil {
|
||||
if a.mappings == nil {
|
||||
http.Error(w, "mappings not configured", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
@@ -138,32 +182,32 @@ func (s *Server) handleMappingUpdate(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
m := mapping.Mapping{ID: id, Name: req.Name, SourceHint: req.SourceHint, EventTypeID: req.EventTypeID, Fields: req.Fields}
|
||||
if !s.validateMapping(w, r, m) {
|
||||
if !a.validateMapping(w, r, m) {
|
||||
return
|
||||
}
|
||||
if err := s.Mappings.UpdateMapping(r.Context(), m); err != nil {
|
||||
if err := a.mappings.UpdateMapping(r.Context(), m); err != nil {
|
||||
if errors.Is(err, storecontract.ErrMappingNotFound) {
|
||||
http.Error(w, "mapping not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
s.Log.ErrorContext(r.Context(), "update mapping", "err", err, "id", id)
|
||||
a.log.ErrorContext(r.Context(), "update mapping", "err", err, "id", id)
|
||||
http.Error(w, "update mapping failed", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
updated, err := s.Mappings.GetMapping(r.Context(), id)
|
||||
updated, err := a.mappings.GetMapping(r.Context(), id)
|
||||
if err != nil || updated == nil {
|
||||
s.Log.ErrorContext(r.Context(), "get mapping after update", "err", err, "id", id)
|
||||
a.log.ErrorContext(r.Context(), "get mapping after update", "err", err, "id", id)
|
||||
http.Error(w, "update mapping failed", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
writeJSON(w, updated)
|
||||
}
|
||||
|
||||
func (s *Server) handleMappingDelete(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.authorizeTaskMutation(w, r) {
|
||||
func (a *mappingsAPI) handleMappingDelete(w http.ResponseWriter, r *http.Request) {
|
||||
if !a.authorize(w, r) {
|
||||
return
|
||||
}
|
||||
if s.Mappings == nil {
|
||||
if a.mappings == nil {
|
||||
http.Error(w, "mappings not configured", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
@@ -172,12 +216,12 @@ func (s *Server) handleMappingDelete(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, "invalid mapping id", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if err := s.Mappings.DeleteMapping(r.Context(), id); err != nil {
|
||||
if err := a.mappings.DeleteMapping(r.Context(), id); err != nil {
|
||||
if errors.Is(err, storecontract.ErrMappingNotFound) {
|
||||
http.Error(w, "mapping not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
s.Log.ErrorContext(r.Context(), "delete mapping", "err", err, "id", id)
|
||||
a.log.ErrorContext(r.Context(), "delete mapping", "err", err, "id", id)
|
||||
http.Error(w, "delete mapping failed", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
@@ -192,12 +236,12 @@ type mappingPreviewRequest struct {
|
||||
Fields []mapping.Field `json:"fields"`
|
||||
}
|
||||
|
||||
func (s *Server) handleMappingPreview(w http.ResponseWriter, r *http.Request) {
|
||||
if s.Mappings == nil {
|
||||
func (a *mappingsAPI) handleMappingPreview(w http.ResponseWriter, r *http.Request) {
|
||||
if a.mappings == nil {
|
||||
http.Error(w, "mappings not configured", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
if s.Captures == nil {
|
||||
if a.captures == nil {
|
||||
http.Error(w, "captures not configured", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
@@ -205,9 +249,9 @@ func (s *Server) handleMappingPreview(w http.ResponseWriter, r *http.Request) {
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
capture, err := s.captureByID(r.Context(), req.CaptureID)
|
||||
capture, err := a.captureByID(r.Context(), req.CaptureID)
|
||||
if err != nil {
|
||||
s.Log.ErrorContext(r.Context(), "get capture for preview", "err", err, "capture_id", req.CaptureID)
|
||||
a.log.ErrorContext(r.Context(), "get capture for preview", "err", err, "capture_id", req.CaptureID)
|
||||
http.Error(w, "preview failed", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
@@ -225,8 +269,8 @@ func (s *Server) handleMappingPreview(w http.ResponseWriter, r *http.Request) {
|
||||
// captureByID finds one captured event by ID. CaptureStore exposes only
|
||||
// ListCaptures, so this scans the newest window rather than adding a new store
|
||||
// method for a single low-volume caller.
|
||||
func (s *Server) captureByID(ctx context.Context, id string) (*storecontract.CapturedEvent, error) {
|
||||
captures, err := s.Captures.ListCaptures(ctx, mappingCaptureScanWindow(s.CaptureMaxEvents))
|
||||
func (a *mappingsAPI) captureByID(ctx context.Context, id string) (*storecontract.CapturedEvent, error) {
|
||||
captures, err := a.captures.ListCaptures(ctx, mappingCaptureScanWindow(a.captureMaxEvents))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -12,9 +12,37 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/domain/org"
|
||||
)
|
||||
|
||||
// orgsAPI owns the /api/orgs routes except selecting the current org, which
|
||||
// sets a cookie and stays with the session code. memberIssuer is the provider
|
||||
// the add-member route binds subjects under.
|
||||
type orgsAPI struct {
|
||||
orgs org.API
|
||||
identities identity.Repository
|
||||
subjects identity.SubjectBinding
|
||||
memberIssuer func(*http.Request) string
|
||||
}
|
||||
|
||||
func newOrgsAPI(s *Server) *orgsAPI {
|
||||
return &orgsAPI{orgs: s.Orgs, identities: s.Identities, subjects: s.Subjects, memberIssuer: s.memberIssuer}
|
||||
}
|
||||
|
||||
func (a *orgsAPI) register(mux *http.ServeMux) {
|
||||
mux.HandleFunc("GET /api/orgs", a.handleOrgsList)
|
||||
mux.HandleFunc("POST /api/orgs", a.handleOrgCreate)
|
||||
mux.HandleFunc("GET /api/orgs/{id}", a.handleOrgGet)
|
||||
mux.HandleFunc("GET /api/orgs/{id}/workspaces", a.handleOrgWorkspacesList)
|
||||
mux.HandleFunc("POST /api/orgs/{id}/workspaces", a.handleOrgWorkspaceCreate)
|
||||
mux.HandleFunc("GET /api/orgs/{id}/members", a.handleOrgMembersList)
|
||||
mux.HandleFunc("POST /api/orgs/{id}/members", a.handleOrgMemberAdd)
|
||||
mux.HandleFunc("PUT /api/orgs/{id}/members/{identity}", a.handleOrgMemberSet)
|
||||
mux.HandleFunc("DELETE /api/orgs/{id}/members/{identity}", a.handleOrgMemberRemove)
|
||||
mux.HandleFunc("GET /api/orgs/{id}/agents", a.handleOrgAgentsList)
|
||||
mux.HandleFunc("PUT /api/orgs/{id}/agents/{identity}", instanceOnly(a.handleOrgAgentAssign))
|
||||
}
|
||||
|
||||
// orgReady answers Unavailable when this process hosts no org store.
|
||||
func (s *Server) orgReady(w http.ResponseWriter) bool {
|
||||
if s.Orgs == nil {
|
||||
func (a *orgsAPI) orgReady(w http.ResponseWriter) bool {
|
||||
if a.orgs == nil {
|
||||
http.Error(w, "orgs unavailable", http.StatusServiceUnavailable)
|
||||
return false
|
||||
}
|
||||
@@ -23,7 +51,7 @@ func (s *Server) orgReady(w http.ResponseWriter) bool {
|
||||
|
||||
// orgInPath resolves the route's {id}: the caller's own org, or any org for
|
||||
// an instance admin. Another tenant reads as not found rather than leaking.
|
||||
func (s *Server) orgInPath(w http.ResponseWriter, r *http.Request) (org.OrgID, bool) {
|
||||
func (a *orgsAPI) orgInPath(w http.ResponseWriter, r *http.Request) (org.OrgID, bool) {
|
||||
id := org.OrgID(r.PathValue("id"))
|
||||
if id != policyOrg(r) && !instanceOwner(r) {
|
||||
http.Error(w, "org not found", http.StatusNotFound)
|
||||
@@ -35,11 +63,11 @@ func (s *Server) orgInPath(w http.ResponseWriter, r *http.Request) (org.OrgID, b
|
||||
// handleOrgsList lists every org to an instance admin and the caller's own
|
||||
// and member orgs to anyone else, naming the org the caller acts in and the
|
||||
// ones it may select.
|
||||
func (s *Server) handleOrgsList(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.orgReady(w) {
|
||||
func (a *orgsAPI) handleOrgsList(w http.ResponseWriter, r *http.Request) {
|
||||
if !a.orgReady(w) {
|
||||
return
|
||||
}
|
||||
values, err := s.Orgs.ListOrgs(r.Context())
|
||||
values, err := a.orgs.ListOrgs(r.Context())
|
||||
if err != nil {
|
||||
writeOrgError(w, err)
|
||||
return
|
||||
@@ -60,15 +88,15 @@ func (s *Server) handleOrgsList(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
// handleOrgCreate creates an org with its default workspace and first owner.
|
||||
// Only an instance admin may.
|
||||
func (s *Server) handleOrgCreate(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.orgReady(w) {
|
||||
func (a *orgsAPI) handleOrgCreate(w http.ResponseWriter, r *http.Request) {
|
||||
if !a.orgReady(w) {
|
||||
return
|
||||
}
|
||||
if !instanceOwner(r) {
|
||||
http.Error(w, "only an instance admin creates orgs", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
creator, ok := s.Orgs.(org.Creator)
|
||||
creator, ok := a.orgs.(org.Creator)
|
||||
if !ok {
|
||||
http.Error(w, "org creation unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
@@ -91,15 +119,15 @@ func (s *Server) handleOrgCreate(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, map[string]any{"org": created})
|
||||
}
|
||||
|
||||
func (s *Server) handleOrgGet(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.orgReady(w) {
|
||||
func (a *orgsAPI) handleOrgGet(w http.ResponseWriter, r *http.Request) {
|
||||
if !a.orgReady(w) {
|
||||
return
|
||||
}
|
||||
id, ok := s.orgInPath(w, r)
|
||||
id, ok := a.orgInPath(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
value, err := s.Orgs.GetOrg(r.Context(), id)
|
||||
value, err := a.orgs.GetOrg(r.Context(), id)
|
||||
if err != nil {
|
||||
writeOrgError(w, err)
|
||||
return
|
||||
@@ -107,15 +135,15 @@ func (s *Server) handleOrgGet(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, map[string]any{"org": value})
|
||||
}
|
||||
|
||||
func (s *Server) handleOrgWorkspacesList(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.orgReady(w) {
|
||||
func (a *orgsAPI) handleOrgWorkspacesList(w http.ResponseWriter, r *http.Request) {
|
||||
if !a.orgReady(w) {
|
||||
return
|
||||
}
|
||||
id, ok := s.orgInPath(w, r)
|
||||
id, ok := a.orgInPath(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
values, err := s.Orgs.ListWorkspaces(r.Context(), id)
|
||||
values, err := a.orgs.ListWorkspaces(r.Context(), id)
|
||||
if err != nil {
|
||||
writeOrgError(w, err)
|
||||
return
|
||||
@@ -126,11 +154,11 @@ func (s *Server) handleOrgWorkspacesList(w http.ResponseWriter, r *http.Request)
|
||||
writeJSON(w, map[string]any{"workspaces": values})
|
||||
}
|
||||
|
||||
func (s *Server) handleOrgWorkspaceCreate(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.orgReady(w) {
|
||||
func (a *orgsAPI) handleOrgWorkspaceCreate(w http.ResponseWriter, r *http.Request) {
|
||||
if !a.orgReady(w) {
|
||||
return
|
||||
}
|
||||
id, ok := s.orgInPath(w, r)
|
||||
id, ok := a.orgInPath(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
@@ -143,7 +171,7 @@ func (s *Server) handleOrgWorkspaceCreate(w http.ResponseWriter, r *http.Request
|
||||
http.Error(w, "invalid workspace: "+err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
value, err := s.Orgs.CreateWorkspace(r.Context(), org.Workspace{
|
||||
value, err := a.orgs.CreateWorkspace(r.Context(), org.Workspace{
|
||||
ID: org.WorkspaceID(request.ID), OrgID: id, Name: request.Name, Environment: request.Environment,
|
||||
})
|
||||
if err != nil {
|
||||
@@ -154,15 +182,15 @@ func (s *Server) handleOrgWorkspaceCreate(w http.ResponseWriter, r *http.Request
|
||||
writeJSON(w, map[string]any{"workspace": value})
|
||||
}
|
||||
|
||||
func (s *Server) handleOrgMembersList(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.orgReady(w) {
|
||||
func (a *orgsAPI) handleOrgMembersList(w http.ResponseWriter, r *http.Request) {
|
||||
if !a.orgReady(w) {
|
||||
return
|
||||
}
|
||||
id, ok := s.orgInPath(w, r)
|
||||
id, ok := a.orgInPath(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
values, err := s.Orgs.ListMembers(r.Context(), id)
|
||||
values, err := a.orgs.ListMembers(r.Context(), id)
|
||||
if err != nil {
|
||||
writeOrgError(w, err)
|
||||
return
|
||||
@@ -175,11 +203,11 @@ func (s *Server) handleOrgMembersList(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
// handleOrgMemberSet grants or moves one identity's role in the caller's org,
|
||||
// or in one workspace when the body names one.
|
||||
func (s *Server) handleOrgMemberSet(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.orgReady(w) {
|
||||
func (a *orgsAPI) handleOrgMemberSet(w http.ResponseWriter, r *http.Request) {
|
||||
if !a.orgReady(w) {
|
||||
return
|
||||
}
|
||||
id, ok := s.orgInPath(w, r)
|
||||
id, ok := a.orgInPath(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
@@ -197,10 +225,10 @@ func (s *Server) handleOrgMemberSet(w http.ResponseWriter, r *http.Request) {
|
||||
WorkspaceID: org.WorkspaceID(request.Workspace),
|
||||
Role: org.Role(request.Role),
|
||||
}
|
||||
if !s.mayChangeMembership(w, r, membership, membership.Role) {
|
||||
if !a.mayChangeMembership(w, r, membership, membership.Role) {
|
||||
return
|
||||
}
|
||||
if err := s.Orgs.EnsureMembership(r.Context(), membership); err != nil {
|
||||
if err := a.orgs.EnsureMembership(r.Context(), membership); err != nil {
|
||||
writeOrgError(w, err)
|
||||
return
|
||||
}
|
||||
@@ -211,23 +239,23 @@ func (s *Server) handleOrgMemberSet(w http.ResponseWriter, r *http.Request) {
|
||||
// their email, creating the identity and binding it so that person's next
|
||||
// sign-in resolves to it with this role. An already-bound subject keeps its
|
||||
// identity and only gains the membership.
|
||||
func (s *Server) handleOrgMemberAdd(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.orgReady(w) {
|
||||
func (a *orgsAPI) handleOrgMemberAdd(w http.ResponseWriter, r *http.Request) {
|
||||
if !a.orgReady(w) {
|
||||
return
|
||||
}
|
||||
id, ok := s.orgInPath(w, r)
|
||||
id, ok := a.orgInPath(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if s.Subjects == nil || s.Identities == nil || s.memberIssuer(r) == "" {
|
||||
if a.subjects == nil || a.identities == nil || a.memberIssuer(r) == "" {
|
||||
http.Error(w, "adding a person needs a configured identity provider", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
request, bound, name, ok := s.decodeMemberAdd(w, r)
|
||||
request, bound, name, ok := a.decodeMemberAdd(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
existing, err := s.Subjects.ResolveSubject(r.Context(), bound)
|
||||
existing, err := a.subjects.ResolveSubject(r.Context(), bound)
|
||||
if err != nil && !errors.Is(err, identity.ErrNotFound) {
|
||||
writeIdentityError(w, err)
|
||||
return
|
||||
@@ -243,13 +271,13 @@ func (s *Server) handleOrgMemberAdd(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
}
|
||||
if !s.mayChangeMembership(w, r, membership, membership.Role) {
|
||||
if !a.mayChangeMembership(w, r, membership, membership.Role) {
|
||||
return
|
||||
}
|
||||
if unbound && !s.createBoundIdentity(w, r, membership.IdentityID, name, bound) {
|
||||
if unbound && !a.createBoundIdentity(w, r, membership.IdentityID, name, bound) {
|
||||
return
|
||||
}
|
||||
if err := s.Orgs.EnsureMembership(r.Context(), membership); err != nil {
|
||||
if err := a.orgs.EnsureMembership(r.Context(), membership); err != nil {
|
||||
writeOrgError(w, err)
|
||||
return
|
||||
}
|
||||
@@ -268,7 +296,7 @@ type memberAddRequest struct {
|
||||
// decodeMemberAdd reads and validates an add-member body, returning the
|
||||
// provider subject it names and the display name to give a new identity. It
|
||||
// has written the error when ok is false.
|
||||
func (s *Server) decodeMemberAdd(w http.ResponseWriter, r *http.Request) (request memberAddRequest, bound identity.Subject, name string, ok bool) {
|
||||
func (a *orgsAPI) decodeMemberAdd(w http.ResponseWriter, r *http.Request) (request memberAddRequest, bound identity.Subject, name string, ok bool) {
|
||||
request, ok = decodeBody[memberAddRequest](w, r)
|
||||
if !ok {
|
||||
return
|
||||
@@ -280,9 +308,9 @@ func (s *Server) decodeMemberAdd(w http.ResponseWriter, r *http.Request) (reques
|
||||
http.Error(w, "give either a subject or an email", http.StatusBadRequest)
|
||||
return request, bound, name, false
|
||||
case subject != "":
|
||||
bound, name = identity.Subject{Issuer: s.memberIssuer(r), Subject: subject}, cmp.Or(name, subject)
|
||||
bound, name = identity.Subject{Issuer: a.memberIssuer(r), Subject: subject}, cmp.Or(name, subject)
|
||||
default:
|
||||
bound, name = identity.EmailSubject(s.memberIssuer(r), email), cmp.Or(name, email)
|
||||
bound, name = identity.EmailSubject(a.memberIssuer(r), email), cmp.Or(name, email)
|
||||
}
|
||||
if err := org.Role(request.Role).Validate(); err != nil {
|
||||
writeOrgError(w, err)
|
||||
@@ -293,7 +321,7 @@ func (s *Server) decodeMemberAdd(w http.ResponseWriter, r *http.Request) (reques
|
||||
|
||||
// createBoundIdentity makes a user identity and binds subject to it, having
|
||||
// written the error and returned false when either step fails.
|
||||
func (s *Server) createBoundIdentity(w http.ResponseWriter, r *http.Request, id identity.IdentityID, name string, subject identity.Subject) bool {
|
||||
func (a *orgsAPI) createBoundIdentity(w http.ResponseWriter, r *http.Request, id identity.IdentityID, name string, subject identity.Subject) bool {
|
||||
audit, err := webAudit(r.Context())
|
||||
if err != nil {
|
||||
http.Error(w, "cannot create request ID", http.StatusInternalServerError)
|
||||
@@ -301,10 +329,10 @@ func (s *Server) createBoundIdentity(w http.ResponseWriter, r *http.Request, id
|
||||
}
|
||||
value, err := identity.New(id, identity.KindUser, name)
|
||||
if err == nil {
|
||||
_, err = s.Identities.Create(r.Context(), value, audit)
|
||||
_, err = a.identities.Create(r.Context(), value, audit)
|
||||
}
|
||||
if err == nil {
|
||||
err = s.Subjects.BindSubject(r.Context(), id, subject, audit)
|
||||
err = a.subjects.BindSubject(r.Context(), id, subject, audit)
|
||||
}
|
||||
if err != nil {
|
||||
writeIdentityError(w, err)
|
||||
@@ -313,11 +341,11 @@ func (s *Server) createBoundIdentity(w http.ResponseWriter, r *http.Request, id
|
||||
return true
|
||||
}
|
||||
|
||||
func (s *Server) handleOrgMemberRemove(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.orgReady(w) {
|
||||
func (a *orgsAPI) handleOrgMemberRemove(w http.ResponseWriter, r *http.Request) {
|
||||
if !a.orgReady(w) {
|
||||
return
|
||||
}
|
||||
id, ok := s.orgInPath(w, r)
|
||||
id, ok := a.orgInPath(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
@@ -326,25 +354,25 @@ func (s *Server) handleOrgMemberRemove(w http.ResponseWriter, r *http.Request) {
|
||||
OrgID: id,
|
||||
WorkspaceID: org.WorkspaceID(r.URL.Query().Get("workspace")),
|
||||
}
|
||||
if !s.mayChangeMembership(w, r, membership, "") {
|
||||
if !a.mayChangeMembership(w, r, membership, "") {
|
||||
return
|
||||
}
|
||||
if err := s.Orgs.RemoveMembership(r.Context(), membership); err != nil {
|
||||
if err := a.orgs.RemoveMembership(r.Context(), membership); err != nil {
|
||||
writeOrgError(w, err)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (s *Server) handleOrgAgentAssign(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.orgReady(w) {
|
||||
func (a *orgsAPI) handleOrgAgentAssign(w http.ResponseWriter, r *http.Request) {
|
||||
if !a.orgReady(w) {
|
||||
return
|
||||
}
|
||||
id, ok := s.orgInPath(w, r)
|
||||
id, ok := a.orgInPath(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
err := s.Orgs.AssignAgent(r.Context(), org.AgentAssignment{
|
||||
err := a.orgs.AssignAgent(r.Context(), org.AgentAssignment{
|
||||
IdentityID: identity.IdentityID(r.PathValue("identity")), OrgID: id,
|
||||
})
|
||||
if err != nil {
|
||||
@@ -362,7 +390,7 @@ func (s *Server) handleOrgAgentAssign(w http.ResponseWriter, r *http.Request) {
|
||||
// of the org: member management is an admin's grant, and without this an
|
||||
// admin could make themselves owner -- and an owner of org-sys owns the
|
||||
// instance.
|
||||
func (s *Server) mayChangeMembership(w http.ResponseWriter, r *http.Request, target org.Membership, grant org.Role) bool {
|
||||
func (a *orgsAPI) mayChangeMembership(w http.ResponseWriter, r *http.Request, target org.Membership, grant org.Role) bool {
|
||||
principal, ok := access.PrincipalFromContext(r.Context())
|
||||
if !ok {
|
||||
principal = access.SharedTokenOwner()
|
||||
@@ -372,7 +400,7 @@ func (s *Server) mayChangeMembership(w http.ResponseWriter, r *http.Request, tar
|
||||
}
|
||||
touchesOwner := grant == org.RoleOwner
|
||||
if !touchesOwner {
|
||||
members, err := s.Orgs.ListMembers(r.Context(), target.OrgID)
|
||||
members, err := a.orgs.ListMembers(r.Context(), target.OrgID)
|
||||
if err != nil {
|
||||
writeOrgError(w, err)
|
||||
return false
|
||||
@@ -406,28 +434,15 @@ func writeOrgError(w http.ResponseWriter, err error) {
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) memberIssuer(r *http.Request) string {
|
||||
if store, ok := s.authenticationSettings(); ok {
|
||||
value, err := store.AuthenticationSettings(r.Context())
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
if value.PublicURL != "" {
|
||||
return value.OIDCIssuer
|
||||
}
|
||||
}
|
||||
return s.Issuer
|
||||
}
|
||||
|
||||
func (s *Server) handleOrgAgentsList(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.orgReady(w) {
|
||||
func (a *orgsAPI) handleOrgAgentsList(w http.ResponseWriter, r *http.Request) {
|
||||
if !a.orgReady(w) {
|
||||
return
|
||||
}
|
||||
id, ok := s.orgInPath(w, r)
|
||||
id, ok := a.orgInPath(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
reader, ok := s.Orgs.(org.AgentAssignments)
|
||||
reader, ok := a.orgs.(org.AgentAssignments)
|
||||
if !ok {
|
||||
http.Error(w, "agent assignments unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
@@ -438,12 +453,12 @@ func (s *Server) handleOrgAgentsList(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
agents := make([]identity.Identity, 0, len(values))
|
||||
if s.Identities == nil {
|
||||
if a.identities == nil {
|
||||
http.Error(w, "identity authority unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
for _, assignment := range values {
|
||||
value, err := s.Identities.Get(r.Context(), assignment.IdentityID)
|
||||
value, err := a.identities.Get(r.Context(), assignment.IdentityID)
|
||||
if err != nil {
|
||||
writeIdentityError(w, err)
|
||||
return
|
||||
@@ -117,17 +117,8 @@ func (f *fakeOrgs) AssignAgent(_ context.Context, value org.AgentAssignment) err
|
||||
// the real server mounts.
|
||||
func orgRoutes(s *Server) http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /api/orgs", s.handleOrgsList)
|
||||
mux.HandleFunc("POST /api/orgs", s.handleOrgCreate)
|
||||
newOrgsAPI(s).register(mux)
|
||||
mux.HandleFunc("PUT /api/orgs/current", s.handleOrgSelect)
|
||||
mux.HandleFunc("GET /api/orgs/{id}", s.handleOrgGet)
|
||||
mux.HandleFunc("GET /api/orgs/{id}/workspaces", s.handleOrgWorkspacesList)
|
||||
mux.HandleFunc("POST /api/orgs/{id}/workspaces", s.handleOrgWorkspaceCreate)
|
||||
mux.HandleFunc("GET /api/orgs/{id}/members", s.handleOrgMembersList)
|
||||
mux.HandleFunc("POST /api/orgs/{id}/members", s.handleOrgMemberAdd)
|
||||
mux.HandleFunc("PUT /api/orgs/{id}/members/{identity}", s.handleOrgMemberSet)
|
||||
mux.HandleFunc("DELETE /api/orgs/{id}/members/{identity}", s.handleOrgMemberRemove)
|
||||
mux.HandleFunc("PUT /api/orgs/{id}/agents/{identity}", s.handleOrgAgentAssign)
|
||||
return s.requireToken(s.authorize(mux))
|
||||
}
|
||||
|
||||
@@ -16,15 +16,15 @@ const maxTokenNameLength = 40
|
||||
// Personal API tokens belong to the signed-in person; the State Store acts
|
||||
// on the principal the request carries, so these handlers name no one.
|
||||
|
||||
func (s *Server) handlePersonalTokensList(w http.ResponseWriter, r *http.Request) {
|
||||
func (a *identitiesAPI) handlePersonalTokensList(w http.ResponseWriter, r *http.Request) {
|
||||
if !personalTokenOwner(r) {
|
||||
writeJSON(w, map[string]any{"tokens": []identity.PersonalToken{}, "available": false})
|
||||
return
|
||||
}
|
||||
if !s.personalTokensReady(w, r) {
|
||||
if !a.personalTokensReady(w, r) {
|
||||
return
|
||||
}
|
||||
tokens, err := s.PersonalTokens.ListPersonalTokens(r.Context())
|
||||
tokens, err := a.tokens.ListPersonalTokens(r.Context())
|
||||
if err != nil {
|
||||
writeIdentityError(w, err)
|
||||
return
|
||||
@@ -37,8 +37,8 @@ func (s *Server) handlePersonalTokensList(w http.ResponseWriter, r *http.Request
|
||||
|
||||
// handlePersonalTokenCreate makes a token here and sends only its hash to the
|
||||
// State Store; the response is the one time the token is shown.
|
||||
func (s *Server) handlePersonalTokenCreate(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.personalTokensReady(w, r) {
|
||||
func (a *identitiesAPI) handlePersonalTokenCreate(w http.ResponseWriter, r *http.Request) {
|
||||
if !a.personalTokensReady(w, r) {
|
||||
return
|
||||
}
|
||||
name, expiresAt, ok := decodeTokenRequest(w, r)
|
||||
@@ -50,7 +50,7 @@ func (s *Server) handlePersonalTokenCreate(w http.ResponseWriter, r *http.Reques
|
||||
http.Error(w, "cannot create token", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
if err := s.PersonalTokens.AddPersonalToken(r.Context(), subject, name, expiresAt); err != nil {
|
||||
if err := a.tokens.AddPersonalToken(r.Context(), subject, name, expiresAt); err != nil {
|
||||
writeIdentityError(w, err)
|
||||
return
|
||||
}
|
||||
@@ -88,11 +88,11 @@ func decodeTokenRequest(w http.ResponseWriter, r *http.Request) (string, *time.T
|
||||
return name, expiresAt, true
|
||||
}
|
||||
|
||||
func (s *Server) handlePersonalTokenRevoke(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.personalTokensReady(w, r) {
|
||||
func (a *identitiesAPI) handlePersonalTokenRevoke(w http.ResponseWriter, r *http.Request) {
|
||||
if !a.personalTokensReady(w, r) {
|
||||
return
|
||||
}
|
||||
if err := s.PersonalTokens.RevokePersonalToken(r.Context(), r.PathValue("id")); err != nil {
|
||||
if err := a.tokens.RevokePersonalToken(r.Context(), r.PathValue("id")); err != nil {
|
||||
writeIdentityError(w, err)
|
||||
return
|
||||
}
|
||||
@@ -104,13 +104,13 @@ func personalTokenOwner(r *http.Request) bool {
|
||||
return ok && p.IdentityID != "" && p.IdentityID != identity.SystemID
|
||||
}
|
||||
|
||||
func (s *Server) personalTokensReady(w http.ResponseWriter, r *http.Request) bool {
|
||||
func (a *identitiesAPI) personalTokensReady(w http.ResponseWriter, r *http.Request) bool {
|
||||
if !personalTokenOwner(r) {
|
||||
http.Error(w, "Personal tokens need a signed-in person.", http.StatusForbidden)
|
||||
return false
|
||||
}
|
||||
|
||||
if s.PersonalTokens == nil {
|
||||
if a.tokens == nil {
|
||||
http.Error(w, "personal tokens unavailable", http.StatusServiceUnavailable)
|
||||
return false
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
@@ -79,15 +80,38 @@ func runView(r scheduling.Run) scheduleRunView {
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) ownerView(ctx context.Context, owner scheduling.Owner, names map[org.OrgID]string) scheduleOwnerView {
|
||||
// schedulesAPI owns the /api/schedules routes. They are org-scoped, not
|
||||
// instance-only: the system org sees every schedule, any other org only its
|
||||
// own, and the handlers enforce that ownership.
|
||||
type schedulesAPI struct {
|
||||
schedules ScheduleStore
|
||||
orgs org.API
|
||||
dispatches storecontract.DispatchLedger
|
||||
log *slog.Logger
|
||||
authorize func(http.ResponseWriter, *http.Request) bool
|
||||
}
|
||||
|
||||
func newSchedulesAPI(s *Server) *schedulesAPI {
|
||||
return &schedulesAPI{schedules: s.Schedules, orgs: s.Orgs, dispatches: s.Dispatches, log: s.Log, authorize: s.authorizeTaskMutation}
|
||||
}
|
||||
|
||||
func (a *schedulesAPI) register(mux *http.ServeMux) {
|
||||
mux.HandleFunc("GET /api/schedules", a.handleSchedules)
|
||||
mux.HandleFunc("PUT /api/schedules/{id}", a.handleSchedulePut)
|
||||
mux.HandleFunc("DELETE /api/schedules/{id}", a.handleScheduleDelete)
|
||||
mux.HandleFunc("GET /api/schedules/{id}/runs", a.handleScheduleRuns)
|
||||
mux.HandleFunc("POST /api/schedules/{id}/runs", a.handleScheduleRunNow)
|
||||
}
|
||||
|
||||
func (a *schedulesAPI) ownerView(ctx context.Context, owner scheduling.Owner, names map[org.OrgID]string) scheduleOwnerView {
|
||||
view := scheduleOwnerView{Kind: owner.Kind, ID: owner.ID}
|
||||
id := org.OrgID(owner.ID)
|
||||
if owner.Kind == scheduling.OwnerInstance {
|
||||
id = org.DefaultOrgID
|
||||
}
|
||||
name, ok := names[id]
|
||||
if !ok && s.Orgs != nil {
|
||||
if found, err := s.Orgs.GetOrg(ctx, id); err == nil {
|
||||
if !ok && a.orgs != nil {
|
||||
if found, err := a.orgs.GetOrg(ctx, id); err == nil {
|
||||
name = found.Name
|
||||
}
|
||||
names[id] = name
|
||||
@@ -96,9 +120,9 @@ func (s *Server) ownerView(ctx context.Context, owner scheduling.Owner, names ma
|
||||
return view
|
||||
}
|
||||
|
||||
func (s *Server) scheduleView(ctx context.Context, sched scheduling.Schedule, names map[org.OrgID]string) scheduleView {
|
||||
func (a *schedulesAPI) scheduleView(ctx context.Context, sched scheduling.Schedule, names map[org.OrgID]string) scheduleView {
|
||||
view := scheduleView{
|
||||
ID: sched.ID, Name: sched.Name, Owner: s.ownerView(ctx, sched.Owner, names),
|
||||
ID: sched.ID, Name: sched.Name, Owner: a.ownerView(ctx, sched.Owner, names),
|
||||
Enabled: sched.Enabled, BuiltIn: sched.BuiltIn, Timing: sched.Timing,
|
||||
NextRun: optionalTime(sched.NextRun),
|
||||
}
|
||||
@@ -109,7 +133,7 @@ func (s *Server) scheduleView(ctx context.Context, sched scheduling.Schedule, na
|
||||
return view
|
||||
}
|
||||
|
||||
func (s *Server) scheduleError(ctx context.Context, w http.ResponseWriter, op string, err error) {
|
||||
func (a *schedulesAPI) scheduleError(ctx context.Context, w http.ResponseWriter, op string, err error) {
|
||||
switch {
|
||||
case errors.Is(err, scheduling.ErrNotFound):
|
||||
http.Error(w, "schedule not found", http.StatusNotFound)
|
||||
@@ -118,13 +142,13 @@ func (s *Server) scheduleError(ctx context.Context, w http.ResponseWriter, op st
|
||||
case errors.Is(err, scheduling.ErrInvalidSpec):
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
default:
|
||||
s.Log.ErrorContext(ctx, op, "err", err)
|
||||
a.log.ErrorContext(ctx, op, "err", err)
|
||||
http.Error(w, op+" failed", http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) schedulesReady(w http.ResponseWriter) bool {
|
||||
if s.Schedules == nil {
|
||||
func (a *schedulesAPI) schedulesReady(w http.ResponseWriter) bool {
|
||||
if a.schedules == nil {
|
||||
http.Error(w, "schedules unavailable", http.StatusServiceUnavailable)
|
||||
return false
|
||||
}
|
||||
@@ -152,15 +176,15 @@ func scheduleOwned(instance bool, orgID org.OrgID, sched scheduling.Schedule) bo
|
||||
|
||||
// ownedSchedule reads the named schedule and reports whether the acting org
|
||||
// owns it, answering not found when it does not exist or belongs elsewhere.
|
||||
func (s *Server) ownedSchedule(w http.ResponseWriter, r *http.Request, id string) (scheduling.Schedule, bool) {
|
||||
func (a *schedulesAPI) ownedSchedule(w http.ResponseWriter, r *http.Request, id string) (scheduling.Schedule, bool) {
|
||||
orgID, instance := scheduleScope(r)
|
||||
sched, err := s.Schedules.GetSchedule(r.Context(), id)
|
||||
sched, err := a.schedules.GetSchedule(r.Context(), id)
|
||||
switch {
|
||||
case errors.Is(err, scheduling.ErrNotFound):
|
||||
http.Error(w, "schedule not found", http.StatusNotFound)
|
||||
return scheduling.Schedule{}, false
|
||||
case err != nil:
|
||||
s.scheduleError(r.Context(), w, "get schedule", err)
|
||||
a.scheduleError(r.Context(), w, "get schedule", err)
|
||||
return scheduling.Schedule{}, false
|
||||
case !scheduleOwned(instance, orgID, sched):
|
||||
http.Error(w, "schedule not found", http.StatusNotFound)
|
||||
@@ -169,13 +193,13 @@ func (s *Server) ownedSchedule(w http.ResponseWriter, r *http.Request, id string
|
||||
return sched, true
|
||||
}
|
||||
|
||||
func (s *Server) handleSchedules(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.schedulesReady(w) {
|
||||
func (a *schedulesAPI) handleSchedules(w http.ResponseWriter, r *http.Request) {
|
||||
if !a.schedulesReady(w) {
|
||||
return
|
||||
}
|
||||
list, err := s.Schedules.ListSchedules(r.Context())
|
||||
list, err := a.schedules.ListSchedules(r.Context())
|
||||
if err != nil {
|
||||
s.scheduleError(r.Context(), w, "list schedules", err)
|
||||
a.scheduleError(r.Context(), w, "list schedules", err)
|
||||
return
|
||||
}
|
||||
orgID, instance := scheduleScope(r)
|
||||
@@ -185,7 +209,7 @@ func (s *Server) handleSchedules(w http.ResponseWriter, r *http.Request) {
|
||||
if !scheduleOwned(instance, orgID, sched) {
|
||||
continue
|
||||
}
|
||||
views = append(views, s.scheduleView(r.Context(), sched, names))
|
||||
views = append(views, a.scheduleView(r.Context(), sched, names))
|
||||
}
|
||||
writeJSON(w, map[string]any{"schedules": views})
|
||||
}
|
||||
@@ -194,8 +218,8 @@ func (s *Server) handleSchedules(w http.ResponseWriter, r *http.Request) {
|
||||
// change on it. A new schedule belongs to the instance when the system org
|
||||
// writes it and to the acting org otherwise; an existing schedule must be the
|
||||
// acting org's own.
|
||||
func (s *Server) handleSchedulePut(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.authorizeTaskMutation(w, r) || !s.schedulesReady(w) {
|
||||
func (a *schedulesAPI) handleSchedulePut(w http.ResponseWriter, r *http.Request) {
|
||||
if !a.authorize(w, r) || !a.schedulesReady(w) {
|
||||
return
|
||||
}
|
||||
var input scheduleInput
|
||||
@@ -205,7 +229,7 @@ func (s *Server) handleSchedulePut(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
id := r.PathValue("id")
|
||||
orgID, instance := scheduleScope(r)
|
||||
sched, err := s.Schedules.GetSchedule(r.Context(), id)
|
||||
sched, err := a.schedules.GetSchedule(r.Context(), id)
|
||||
switch {
|
||||
case errors.Is(err, scheduling.ErrNotFound):
|
||||
owner := scheduling.Owner{Kind: scheduling.OwnerInstance}
|
||||
@@ -214,45 +238,45 @@ func (s *Server) handleSchedulePut(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
sched = scheduling.Schedule{ID: id, Owner: owner}
|
||||
case err != nil:
|
||||
s.scheduleError(r.Context(), w, "get schedule", err)
|
||||
a.scheduleError(r.Context(), w, "get schedule", err)
|
||||
return
|
||||
case !scheduleOwned(instance, orgID, sched):
|
||||
http.Error(w, "schedule not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
sched.Name, sched.Enabled, sched.Timing = input.Name, input.Enabled, input.Timing
|
||||
saved, err := s.Schedules.PutSchedule(r.Context(), sched)
|
||||
saved, err := a.schedules.PutSchedule(r.Context(), sched)
|
||||
if err != nil {
|
||||
s.scheduleError(r.Context(), w, "save schedule", err)
|
||||
a.scheduleError(r.Context(), w, "save schedule", err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, s.scheduleView(r.Context(), saved, map[org.OrgID]string{}))
|
||||
writeJSON(w, a.scheduleView(r.Context(), saved, map[org.OrgID]string{}))
|
||||
}
|
||||
|
||||
func (s *Server) handleScheduleDelete(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.authorizeTaskMutation(w, r) || !s.schedulesReady(w) {
|
||||
func (a *schedulesAPI) handleScheduleDelete(w http.ResponseWriter, r *http.Request) {
|
||||
if !a.authorize(w, r) || !a.schedulesReady(w) {
|
||||
return
|
||||
}
|
||||
if _, ok := s.ownedSchedule(w, r, r.PathValue("id")); !ok {
|
||||
if _, ok := a.ownedSchedule(w, r, r.PathValue("id")); !ok {
|
||||
return
|
||||
}
|
||||
if err := s.Schedules.DeleteSchedule(r.Context(), r.PathValue("id")); err != nil {
|
||||
s.scheduleError(r.Context(), w, "delete schedule", err)
|
||||
if err := a.schedules.DeleteSchedule(r.Context(), r.PathValue("id")); err != nil {
|
||||
a.scheduleError(r.Context(), w, "delete schedule", err)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (s *Server) handleScheduleRunNow(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.authorizeTaskMutation(w, r) || !s.schedulesReady(w) {
|
||||
func (a *schedulesAPI) handleScheduleRunNow(w http.ResponseWriter, r *http.Request) {
|
||||
if !a.authorize(w, r) || !a.schedulesReady(w) {
|
||||
return
|
||||
}
|
||||
if _, ok := s.ownedSchedule(w, r, r.PathValue("id")); !ok {
|
||||
if _, ok := a.ownedSchedule(w, r, r.PathValue("id")); !ok {
|
||||
return
|
||||
}
|
||||
run, err := s.Schedules.RequestScheduleRun(r.Context(), r.PathValue("id"))
|
||||
run, err := a.schedules.RequestScheduleRun(r.Context(), r.PathValue("id"))
|
||||
if err != nil {
|
||||
s.scheduleError(r.Context(), w, "run schedule", err)
|
||||
a.scheduleError(r.Context(), w, "run schedule", err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, runView(run))
|
||||
@@ -260,34 +284,34 @@ func (s *Server) handleScheduleRunNow(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
// handleScheduleRuns lists a schedule's runs, each with the tasks its firing
|
||||
// started: the binding dispatches recorded against the run's capture.
|
||||
func (s *Server) handleScheduleRuns(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.schedulesReady(w) {
|
||||
func (a *schedulesAPI) handleScheduleRuns(w http.ResponseWriter, r *http.Request) {
|
||||
if !a.schedulesReady(w) {
|
||||
return
|
||||
}
|
||||
if _, ok := s.ownedSchedule(w, r, r.PathValue("id")); !ok {
|
||||
if _, ok := a.ownedSchedule(w, r, r.PathValue("id")); !ok {
|
||||
return
|
||||
}
|
||||
runs, err := s.Schedules.ListScheduleRuns(r.Context(), r.PathValue("id"), scheduleRunsShown)
|
||||
runs, err := a.schedules.ListScheduleRuns(r.Context(), r.PathValue("id"), scheduleRunsShown)
|
||||
if err != nil {
|
||||
s.scheduleError(r.Context(), w, "list schedule runs", err)
|
||||
a.scheduleError(r.Context(), w, "list schedule runs", err)
|
||||
return
|
||||
}
|
||||
views := make([]scheduleRunView, 0, len(runs))
|
||||
for _, run := range runs {
|
||||
view := runView(run)
|
||||
view.TaskIDs = s.runTasks(r.Context(), run.CaptureID)
|
||||
view.TaskIDs = a.runTasks(r.Context(), run.CaptureID)
|
||||
views = append(views, view)
|
||||
}
|
||||
writeJSON(w, map[string]any{"runs": views})
|
||||
}
|
||||
|
||||
func (s *Server) runTasks(ctx context.Context, captureID string) []int64 {
|
||||
if captureID == "" || s.Dispatches == nil {
|
||||
func (a *schedulesAPI) runTasks(ctx context.Context, captureID string) []int64 {
|
||||
if captureID == "" || a.dispatches == nil {
|
||||
return nil
|
||||
}
|
||||
dispatches, err := s.Dispatches.ListDispatches(ctx, storecontract.DispatchFilter{CaptureID: captureID, Limit: 50})
|
||||
dispatches, err := a.dispatches.ListDispatches(ctx, storecontract.DispatchFilter{CaptureID: captureID, Limit: 50})
|
||||
if err != nil {
|
||||
s.Log.WarnContext(ctx, "schedule run tasks unavailable", "capture", captureID, "err", err)
|
||||
a.log.WarnContext(ctx, "schedule run tasks unavailable", "capture", captureID, "err", err)
|
||||
return nil
|
||||
}
|
||||
var ids []int64
|
||||
@@ -99,11 +99,7 @@ func orgSchedule(id, orgID string) scheduling.Schedule {
|
||||
// wrappers the real server mounts.
|
||||
func scheduleRoutes(s *Server) http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /api/schedules", s.handleSchedules)
|
||||
mux.HandleFunc("PUT /api/schedules/{id}", s.handleSchedulePut)
|
||||
mux.HandleFunc("DELETE /api/schedules/{id}", s.handleScheduleDelete)
|
||||
mux.HandleFunc("GET /api/schedules/{id}/runs", s.handleScheduleRuns)
|
||||
mux.HandleFunc("POST /api/schedules/{id}/runs", s.handleScheduleRunNow)
|
||||
newSchedulesAPI(s).register(mux)
|
||||
return s.requireToken(s.authorize(mux))
|
||||
}
|
||||
|
||||
+39
-119
@@ -34,11 +34,6 @@ type Server struct {
|
||||
Accounts identity.Accounts
|
||||
accountRateLimit *ratelimit.Limiter
|
||||
|
||||
// chatAsks holds the chat questions waiting for the operator's answer.
|
||||
chatAsks chatAsks
|
||||
// chatFiles holds the downloads for files chat turns sent.
|
||||
chatFiles chatFiles
|
||||
|
||||
Store storecontract.TaskStore
|
||||
Log *slog.Logger
|
||||
|
||||
@@ -123,13 +118,6 @@ type Server struct {
|
||||
// Audit is the org-scoped audit feed, behind the audit page and the live
|
||||
// tail. Nil answers 503 on every audit route.
|
||||
Audit audit.Store
|
||||
// auditExportOnce initialises auditExportRate; auditExporting and its
|
||||
// mutex admit one export per identity. An export is bounded by its
|
||||
// explicit range, a five-minute deadline and a page cap (see api_audit.go).
|
||||
auditExportOnce sync.Once
|
||||
auditExportRate *ratelimit.Limiter
|
||||
auditExportMu sync.Mutex
|
||||
auditExporting map[string]bool
|
||||
// now is the clock applyState reads staleness against. Nil means
|
||||
// time.Now; tests set it to pin a record's age.
|
||||
now func() time.Time
|
||||
@@ -285,68 +273,44 @@ func (s *Server) Broadcast(e events.Event) {
|
||||
func (s *Server) registerCoreRoutes(mux *http.ServeMux) {
|
||||
mux.HandleFunc("GET /api/summary", s.handleSummary)
|
||||
mux.HandleFunc("GET /api/setup", s.handleSetup)
|
||||
mux.HandleFunc("GET /api/workflows", s.handleWorkflows)
|
||||
mux.HandleFunc("PUT /api/workflows/{id}/enabled", s.handleWorkflowEnabled)
|
||||
mux.HandleFunc("POST /api/work-requests", s.handleWorkRequest)
|
||||
mux.HandleFunc("GET /api/repositories", s.handleRepositories)
|
||||
newWorkflowsAPI(s).register(mux)
|
||||
mux.HandleFunc("POST /api/control-plane/resources/repository-policies/check", s.handleRepositoryCheck)
|
||||
mux.HandleFunc("GET /api/skills", instanceOnly(s.handleSkills))
|
||||
mux.HandleFunc("GET /api/curators", instanceOnly(s.handleCurators))
|
||||
mux.HandleFunc("GET /api/captures", s.handleCaptures)
|
||||
// Schedule routes are org-scoped, not instance-only: the system org sees
|
||||
// every schedule, any other org only its own, and the handlers enforce
|
||||
// that ownership.
|
||||
mux.HandleFunc("GET /api/schedules", s.handleSchedules)
|
||||
mux.HandleFunc("PUT /api/schedules/{id}", s.handleSchedulePut)
|
||||
mux.HandleFunc("DELETE /api/schedules/{id}", s.handleScheduleDelete)
|
||||
mux.HandleFunc("GET /api/schedules/{id}/runs", s.handleScheduleRuns)
|
||||
mux.HandleFunc("POST /api/schedules/{id}/runs", s.handleScheduleRunNow)
|
||||
newSchedulesAPI(s).register(mux)
|
||||
newAuditAPI(s).register(mux)
|
||||
newAlertsAPI(s).register(mux)
|
||||
mux.HandleFunc("GET /api/channels", instanceOnly(s.handleChannels))
|
||||
mux.HandleFunc("POST /api/channels/{id}/reload", instanceOnly(s.handleChannelReload))
|
||||
mux.HandleFunc("GET /api/version", s.handleVersion)
|
||||
mux.HandleFunc("GET /api/capabilities", s.handleCapabilities)
|
||||
mux.HandleFunc("GET /api/audit", s.handleAudit)
|
||||
mux.HandleFunc("GET /api/audit/export", s.handleAuditExport)
|
||||
mux.HandleFunc("GET /api/alerts", s.handleAlerts)
|
||||
mux.HandleFunc("POST /api/alerts/{id}/dismiss", s.handleAlertDismiss)
|
||||
}
|
||||
|
||||
func (s *Server) registerTaskRoutes(mux *http.ServeMux) {
|
||||
mux.HandleFunc("GET /api/tasks", s.handleTasks)
|
||||
mux.HandleFunc("GET /api/task-meta", s.handleTaskMeta)
|
||||
mux.HandleFunc("POST /api/tasks/{id}/action", s.handleTaskAction)
|
||||
mux.HandleFunc("GET /api/tasks/{id}", s.handleTask)
|
||||
mux.HandleFunc("GET /api/tasks/{id}/attempts", s.handleTaskAttempts)
|
||||
mux.HandleFunc("GET /api/tasks/{id}/changes", s.handleTaskChanges)
|
||||
mux.HandleFunc("GET /api/tasks/{id}/debug", s.handleTaskDebug)
|
||||
mux.HandleFunc("GET /api/tasks/{id}/logs", s.handleTaskLogs)
|
||||
mux.HandleFunc("GET /api/tasks/{id}/transcript", s.handleTaskTranscript)
|
||||
mux.HandleFunc("GET /api/tasks/{id}/sandbox", s.handleTaskSandbox)
|
||||
mux.HandleFunc("GET /api/tasks/{id}/logs/download", s.handleTaskLogDownload)
|
||||
newTasksAPI(s).register(mux)
|
||||
}
|
||||
|
||||
func (s *Server) registerMappingAndBindingRoutes(mux *http.ServeMux) {
|
||||
mux.HandleFunc("GET /api/event-types", s.handleEventTypes)
|
||||
mux.HandleFunc("POST /api/event-types", s.handleEventTypeCreate)
|
||||
mux.HandleFunc("PUT /api/event-types/{id}", s.handleEventTypeUpdate)
|
||||
mux.HandleFunc("DELETE /api/event-types/{id}", s.handleEventTypeDelete)
|
||||
mux.HandleFunc("GET /api/mappings", s.handleMappingsList)
|
||||
mux.HandleFunc("POST /api/mappings", s.handleMappingCreate)
|
||||
mux.HandleFunc("GET /api/mappings/{id}", s.handleMappingGet)
|
||||
mux.HandleFunc("PATCH /api/mappings/{id}", s.handleMappingUpdate)
|
||||
mux.HandleFunc("DELETE /api/mappings/{id}", s.handleMappingDelete)
|
||||
mux.HandleFunc("POST /api/mappings/preview", s.handleMappingPreview)
|
||||
mux.HandleFunc("GET /api/bindings", s.handleBindingsList)
|
||||
mux.HandleFunc("POST /api/bindings", s.handleBindingCreate)
|
||||
mux.HandleFunc("GET /api/bindings/{id}", s.handleBindingGet)
|
||||
mux.HandleFunc("PATCH /api/bindings/{id}", s.handleBindingUpdate)
|
||||
mux.HandleFunc("DELETE /api/bindings/{id}", s.handleBindingDelete)
|
||||
mux.HandleFunc("POST /api/bindings/{id}/approve", s.handleBindingTransition("approve", storecontract.BindingStore.ApproveBinding))
|
||||
mux.HandleFunc("POST /api/bindings/{id}/pause", s.handleBindingTransition("pause", storecontract.BindingStore.PauseBinding))
|
||||
mux.HandleFunc("POST /api/bindings/{id}/resume", s.handleBindingTransition("resume", storecontract.BindingStore.ResumeBinding))
|
||||
mux.HandleFunc("GET /api/bindings/{id}/dispatches", s.handleDispatches(func(id string) (storecontract.DispatchFilter, bool) {
|
||||
return storecontract.DispatchFilter{BindingID: id}, id != ""
|
||||
}))
|
||||
// Event types register unconditionally: the list answers {"enabled": false}
|
||||
// when the store is nil. Mappings and sources mount a 503 stub otherwise.
|
||||
newEventTypesAPI(s).register(mux)
|
||||
if s.Mappings == nil {
|
||||
for _, p := range mappingsRoutes {
|
||||
mux.HandleFunc(p, notConfigured("mappings not configured"))
|
||||
}
|
||||
} else {
|
||||
newMappingsAPI(s).register(mux)
|
||||
}
|
||||
// The bindings module owns its routes and registers itself when the store
|
||||
// is configured; the stub keeps the 503 "not configured" answers otherwise.
|
||||
if s.Bindings == nil {
|
||||
for _, p := range bindingsRoutes {
|
||||
mux.HandleFunc(p, notConfigured("bindings not configured"))
|
||||
}
|
||||
} else {
|
||||
newBindingsAPI(s).register(mux)
|
||||
}
|
||||
mux.HandleFunc("GET /api/captures/{id}/dispatches", s.handleDispatches(func(id string) (storecontract.DispatchFilter, bool) {
|
||||
return storecontract.DispatchFilter{CaptureID: id}, id != ""
|
||||
}))
|
||||
@@ -354,80 +318,36 @@ func (s *Server) registerMappingAndBindingRoutes(mux *http.ServeMux) {
|
||||
taskID, err := strconv.ParseInt(id, 10, 64)
|
||||
return storecontract.DispatchFilter{TaskID: taskID}, err == nil && taskID > 0
|
||||
}))
|
||||
mux.HandleFunc("GET /api/sources", s.handleSourcesList)
|
||||
mux.HandleFunc("POST /api/sources", s.handleSourceCreate)
|
||||
mux.HandleFunc("POST /api/sources/{path}/signing", s.handleSourceSigning)
|
||||
mux.HandleFunc("POST /api/sources/{path}/approve-unsigned", s.handleSourceApproveUnsigned)
|
||||
mux.HandleFunc("POST /api/sources/{path}/secret", s.handleSourceSecret)
|
||||
mux.HandleFunc("PUT /api/sources/{path}/name", s.handleSourceName)
|
||||
mux.HandleFunc("PUT /api/sources/{path}/delivery-header", s.handleSourceDeliveryHeader)
|
||||
mux.HandleFunc("DELETE /api/sources/{path}", s.handleSourceDelete)
|
||||
if s.Sources == nil {
|
||||
for _, p := range sourcesRoutes {
|
||||
mux.HandleFunc(p, notConfigured("sources not configured"))
|
||||
}
|
||||
} else {
|
||||
newSourcesAPI(s).register(mux)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) registerHarnessRoutes(mux *http.ServeMux) {
|
||||
mux.HandleFunc("GET /api/harness/bindings", s.handleHarnessBindings)
|
||||
mux.HandleFunc("GET /api/harness/terminal", s.handleHarnessTerminal)
|
||||
newHarnessAPI(s).register(mux)
|
||||
}
|
||||
|
||||
func (s *Server) registerConfigAndLogRoutes(mux *http.ServeMux) {
|
||||
mux.HandleFunc("GET /api/extensions", s.handleExtensions)
|
||||
mux.HandleFunc("POST /api/extensions", s.handleExtensionInstall)
|
||||
mux.HandleFunc("GET /api/extensions/catalogue", s.handleCatalogue)
|
||||
mux.HandleFunc("POST /api/extensions/catalogue/{name}/install", s.handleCatalogueInstall)
|
||||
mux.HandleFunc("POST /api/extensions/{name}/accept", s.handleExtensionAccept)
|
||||
mux.HandleFunc("POST /api/extensions/{name}/update", s.handleExtensionUpdate)
|
||||
mux.HandleFunc("POST /api/extensions/{name}/approve-update", s.handleExtensionApproveUpdate)
|
||||
mux.HandleFunc("POST /api/extensions/{name}/rollback", s.handleExtensionRollback)
|
||||
mux.HandleFunc("PUT /api/extensions/{name}/update-policy", s.handleExtensionUpdatePolicy)
|
||||
mux.HandleFunc("PUT /api/extensions/{name}/enabled", s.handleExtensionEnabled)
|
||||
mux.HandleFunc("DELETE /api/extensions/{name}", s.handleExtensionRemove)
|
||||
mux.HandleFunc("GET /api/control-plane/catalog", s.handleControlPlaneCatalog)
|
||||
newExtensionsAPI(s).register(mux)
|
||||
mux.HandleFunc("GET /api/control-plane/apply-status", instanceOnly(s.handleApplyStatus))
|
||||
mux.HandleFunc("GET /api/services", instanceOnly(s.handleServices))
|
||||
mux.HandleFunc("GET /api/access/policies", s.handleListPolicies)
|
||||
mux.HandleFunc("PUT /api/access/policies", s.handlePutPolicy)
|
||||
mux.HandleFunc("DELETE /api/access/policies", s.handleDeletePolicy)
|
||||
mux.HandleFunc("GET /api/access/denials", s.handleListDenials)
|
||||
mux.HandleFunc("GET /api/control-plane/resources/{kind}", s.handleControlPlaneQuery)
|
||||
mux.HandleFunc("GET /api/control-plane/resources/{kind}/history", s.handleControlPlaneHistory)
|
||||
mux.HandleFunc("POST /api/control-plane/resources/{kind}/commands/{command}", s.handleControlPlaneCommand)
|
||||
mux.HandleFunc("GET /api/identities", instanceOnly(s.handleIdentitiesList))
|
||||
mux.HandleFunc("GET /api/orgs", s.handleOrgsList)
|
||||
mux.HandleFunc("POST /api/orgs", s.handleOrgCreate)
|
||||
newAccessAPI(s).register(mux)
|
||||
newControlPlaneAPI(s).register(mux)
|
||||
newLogsAPI(s).register(mux)
|
||||
newOrgsAPI(s).register(mux)
|
||||
newIdentitiesAPI(s).register(mux)
|
||||
mux.HandleFunc("PUT /api/orgs/current", s.handleOrgSelect)
|
||||
mux.HandleFunc("GET /api/orgs/{id}", s.handleOrgGet)
|
||||
mux.HandleFunc("GET /api/orgs/{id}/workspaces", s.handleOrgWorkspacesList)
|
||||
mux.HandleFunc("POST /api/orgs/{id}/workspaces", s.handleOrgWorkspaceCreate)
|
||||
mux.HandleFunc("GET /api/orgs/{id}/members", s.handleOrgMembersList)
|
||||
mux.HandleFunc("POST /api/orgs/{id}/members", s.handleOrgMemberAdd)
|
||||
mux.HandleFunc("PUT /api/orgs/{id}/members/{identity}", s.handleOrgMemberSet)
|
||||
mux.HandleFunc("DELETE /api/orgs/{id}/members/{identity}", s.handleOrgMemberRemove)
|
||||
mux.HandleFunc("GET /api/orgs/{id}/agents", s.handleOrgAgentsList)
|
||||
mux.HandleFunc("PUT /api/orgs/{id}/agents/{identity}", instanceOnly(s.handleOrgAgentAssign))
|
||||
mux.HandleFunc("GET /api/tokens", s.handlePersonalTokensList)
|
||||
mux.HandleFunc("POST /api/tokens", s.handlePersonalTokenCreate)
|
||||
mux.HandleFunc("DELETE /api/tokens/{id}", s.handlePersonalTokenRevoke)
|
||||
mux.HandleFunc("POST /api/identities", instanceOnly(s.handleIdentityCreate))
|
||||
mux.HandleFunc("POST /api/identities/{id}/{command}", instanceOnly(s.handleIdentityCommand))
|
||||
mux.HandleFunc("POST /api/identities/{id}/tokens", instanceOnly(s.handleIdentityTokenCreate))
|
||||
mux.HandleFunc("GET /api/config", instanceOnly(s.handleConfig))
|
||||
mux.HandleFunc("GET /api/secret-engines", instanceOnly(s.handleSecretEngines))
|
||||
mux.HandleFunc("POST /api/secret-references/check", instanceOnly(s.handleSecretCheck))
|
||||
mux.HandleFunc("GET /api/logs", instanceOnly(s.handleLogs))
|
||||
}
|
||||
|
||||
func (s *Server) registerChatRoutes(mux *http.ServeMux) {
|
||||
mux.HandleFunc("GET /api/chat/sessions", s.handleChatSessions)
|
||||
mux.HandleFunc("GET /api/chat/sessions/{id}/messages", s.handleChatMessages)
|
||||
mux.HandleFunc("GET /api/chat/sessions/{id}/turns", s.handleChatTurns)
|
||||
mux.HandleFunc("POST /api/chat/message", s.handleChatMessage)
|
||||
mux.HandleFunc("POST /api/chat/stream", s.handleChatStream)
|
||||
mux.HandleFunc("POST /api/chat/cancel", s.handleChatCancel)
|
||||
mux.HandleFunc("POST /api/chat/answer", s.handleChatAnswer)
|
||||
mux.HandleFunc("GET /api/chat/file/{token}", s.handleChatFile)
|
||||
mux.HandleFunc("GET /api/chat/update", instanceOnly(s.handleChatUpdate))
|
||||
mux.HandleFunc("POST /api/chat/update/defer", instanceOnly(s.handleChatUpdateDefer))
|
||||
mux.HandleFunc("POST /api/chat/update/install", instanceOnly(s.handleChatUpdateInstall))
|
||||
newChatAPI(s).register(mux)
|
||||
}
|
||||
|
||||
func (s *Server) Handler() http.Handler {
|
||||
|
||||
@@ -0,0 +1,289 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/access"
|
||||
"github.com/samcharles93/archie-core/internal/domain/org"
|
||||
"github.com/samcharles93/archie-core/internal/domain/source"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
)
|
||||
|
||||
// sourcesAPI owns the /api/sources routes. Constructed only when the source
|
||||
// store is configured; Server mounts a 503 stub otherwise.
|
||||
type sourcesAPI struct {
|
||||
sources storecontract.SourceStore
|
||||
log *slog.Logger
|
||||
authorize func(http.ResponseWriter, *http.Request) bool
|
||||
authorizeCreateIn func(http.ResponseWriter, *http.Request, access.ResourceKind, org.WorkspaceID) bool
|
||||
recentRefusals func(*http.Request) map[string]storecontract.CaptureRefusals
|
||||
}
|
||||
|
||||
func newSourcesAPI(s *Server) *sourcesAPI {
|
||||
return &sourcesAPI{
|
||||
sources: s.Sources,
|
||||
log: s.Log,
|
||||
authorize: s.authorizeTaskMutation,
|
||||
authorizeCreateIn: s.authorizeCreateIn,
|
||||
recentRefusals: s.recentRefusals,
|
||||
}
|
||||
}
|
||||
|
||||
// sourcesRoutes lists the method+path patterns the sources module owns, so
|
||||
// the 503 stub mounts exactly the same routes.
|
||||
var sourcesRoutes = []string{
|
||||
"GET /api/sources",
|
||||
"POST /api/sources",
|
||||
"POST /api/sources/{path}/signing",
|
||||
"POST /api/sources/{path}/approve-unsigned",
|
||||
"POST /api/sources/{path}/secret",
|
||||
"PUT /api/sources/{path}/name",
|
||||
"PUT /api/sources/{path}/delivery-header",
|
||||
"DELETE /api/sources/{path}",
|
||||
}
|
||||
|
||||
func (a *sourcesAPI) register(mux *http.ServeMux) {
|
||||
mux.HandleFunc("GET /api/sources", a.handleSourcesList)
|
||||
mux.HandleFunc("POST /api/sources", a.handleSourceCreate)
|
||||
mux.HandleFunc("POST /api/sources/{path}/signing", a.handleSourceSigning)
|
||||
mux.HandleFunc("POST /api/sources/{path}/approve-unsigned", a.handleSourceApproveUnsigned)
|
||||
mux.HandleFunc("POST /api/sources/{path}/secret", a.handleSourceSecret)
|
||||
mux.HandleFunc("PUT /api/sources/{path}/name", a.handleSourceName)
|
||||
mux.HandleFunc("PUT /api/sources/{path}/delivery-header", a.handleSourceDeliveryHeader)
|
||||
mux.HandleFunc("DELETE /api/sources/{path}", a.handleSourceDelete)
|
||||
}
|
||||
|
||||
func (a *sourcesAPI) handleSourcesList(w http.ResponseWriter, r *http.Request) {
|
||||
if a.sources == nil {
|
||||
http.Error(w, "sources not configured", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
list, err := a.sources.ListSources(r.Context())
|
||||
if err != nil {
|
||||
a.log.ErrorContext(r.Context(), "list sources", "err", err)
|
||||
http.Error(w, "list sources failed", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
list = slices.DeleteFunc(list, func(src source.Source) bool { return !listedIn(r, src.WorkspaceID) })
|
||||
for i := range list {
|
||||
list[i].Secret = ""
|
||||
}
|
||||
writeJSON(w, map[string]any{"sources": list, "refusals": a.recentRefusals(r)})
|
||||
}
|
||||
|
||||
func (a *sourcesAPI) handleSourceCreate(w http.ResponseWriter, r *http.Request) {
|
||||
if !a.authorize(w, r) {
|
||||
return
|
||||
}
|
||||
if a.sources == nil {
|
||||
http.Error(w, "sources not configured", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
Path string `json:"path"`
|
||||
// Workspace is the caller's org workspace to create it in; empty is
|
||||
// the default one.
|
||||
Workspace org.WorkspaceID `json:"workspace"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
http.Error(w, "invalid request body: "+err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if !a.authorizeCreateIn(w, r, access.KindSource, req.Workspace) {
|
||||
return
|
||||
}
|
||||
src, err := source.New(req.Path)
|
||||
if errors.Is(err, source.ErrInvalidPath) || errors.Is(err, source.ErrReservedPath) {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if err == nil {
|
||||
src.WorkspaceID = req.Workspace
|
||||
err = a.sources.InsertSource(r.Context(), src)
|
||||
}
|
||||
if err != nil {
|
||||
a.sourceError(w, "create source", err)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
writeJSON(w, src)
|
||||
}
|
||||
|
||||
// handleSourceSigning turns signing on at once, or requests turning it off.
|
||||
func (a *sourcesAPI) handleSourceSigning(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
Signed bool `json:"signed"`
|
||||
}
|
||||
if !a.authorize(w, r) {
|
||||
return
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
http.Error(w, "invalid request body: "+err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
transition := (*source.Source).RequestUnsigned
|
||||
if req.Signed {
|
||||
transition = (*source.Source).RequireSigning
|
||||
}
|
||||
a.transitionSource(w, r, transition)
|
||||
}
|
||||
|
||||
func (a *sourcesAPI) handleSourceApproveUnsigned(w http.ResponseWriter, r *http.Request) {
|
||||
if !a.authorize(w, r) {
|
||||
return
|
||||
}
|
||||
a.transitionSource(w, r, (*source.Source).ApproveUnsigned)
|
||||
}
|
||||
|
||||
// transitionSource applies one domain signing transition and writes it with
|
||||
// the state it was decided from, so a concurrent change is refused.
|
||||
func (a *sourcesAPI) transitionSource(w http.ResponseWriter, r *http.Request, transition func(*source.Source) error) {
|
||||
src, ok := a.loadSource(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
from := src.Signing
|
||||
if err := transition(src); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusConflict)
|
||||
return
|
||||
}
|
||||
if err := a.sources.SetSourceSigning(r.Context(), src.Path, from, src.Signing); err != nil {
|
||||
a.sourceError(w, "set source signing", err)
|
||||
return
|
||||
}
|
||||
src.Secret = ""
|
||||
writeJSON(w, src)
|
||||
}
|
||||
|
||||
// handleSourceSecret generates a new secret and returns it once.
|
||||
func (a *sourcesAPI) handleSourceSecret(w http.ResponseWriter, r *http.Request) {
|
||||
if !a.authorize(w, r) {
|
||||
return
|
||||
}
|
||||
src, ok := a.loadSource(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
secret, err := source.NewSecret()
|
||||
if err == nil {
|
||||
err = a.sources.SetSourceSecret(r.Context(), src.Path, secret)
|
||||
}
|
||||
if err != nil {
|
||||
a.sourceError(w, "set source secret", err)
|
||||
return
|
||||
}
|
||||
src.Secret = secret
|
||||
writeJSON(w, src)
|
||||
}
|
||||
|
||||
// handleSourceName relabels a source; its path does not change.
|
||||
func (a *sourcesAPI) handleSourceName(w http.ResponseWriter, r *http.Request) {
|
||||
if !a.authorize(w, r) {
|
||||
return
|
||||
}
|
||||
src, ok := a.loadSource(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var request struct {
|
||||
Name string `json:"name"`
|
||||
}
|
||||
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4<<10)).Decode(&request); err != nil {
|
||||
http.Error(w, "invalid source name", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
src.Name = strings.TrimSpace(request.Name)
|
||||
if err := a.sources.SetSourceName(r.Context(), src.Path, src.Name); err != nil {
|
||||
a.sourceError(w, "set source name", err)
|
||||
return
|
||||
}
|
||||
src.Secret = ""
|
||||
writeJSON(w, src)
|
||||
}
|
||||
|
||||
// handleSourceDeliveryHeader sets the header that names a source's
|
||||
// deliveries, so a sender's retry dispatches no second run.
|
||||
func (a *sourcesAPI) handleSourceDeliveryHeader(w http.ResponseWriter, r *http.Request) {
|
||||
if !a.authorize(w, r) {
|
||||
return
|
||||
}
|
||||
src, ok := a.loadSource(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var request struct {
|
||||
Header string `json:"header"`
|
||||
}
|
||||
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4<<10)).Decode(&request); err != nil {
|
||||
http.Error(w, "invalid delivery header", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
header, err := source.DeliveryHeader(request.Header)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
src.DeliveryHeader = header
|
||||
if err := a.sources.SetSourceDeliveryHeader(r.Context(), src.Path, header); err != nil {
|
||||
a.sourceError(w, "set source delivery header", err)
|
||||
return
|
||||
}
|
||||
src.Secret = ""
|
||||
writeJSON(w, src)
|
||||
}
|
||||
|
||||
// handleSourceDelete deletes a source no armed binding fires on.
|
||||
func (a *sourcesAPI) handleSourceDelete(w http.ResponseWriter, r *http.Request) {
|
||||
if !a.authorize(w, r) {
|
||||
return
|
||||
}
|
||||
if a.sources == nil {
|
||||
http.Error(w, "sources not configured", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
if err := a.sources.DeleteSource(r.Context(), r.PathValue("path")); err != nil {
|
||||
a.sourceError(w, "delete source", err)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (a *sourcesAPI) loadSource(w http.ResponseWriter, r *http.Request) (*source.Source, bool) {
|
||||
if a.sources == nil {
|
||||
http.Error(w, "sources not configured", http.StatusServiceUnavailable)
|
||||
return nil, false
|
||||
}
|
||||
src, err := a.sources.GetSource(r.Context(), r.PathValue("path"))
|
||||
if err != nil {
|
||||
a.sourceError(w, "get source", err)
|
||||
return nil, false
|
||||
}
|
||||
if src == nil {
|
||||
http.Error(w, "source not found", http.StatusNotFound)
|
||||
return nil, false
|
||||
}
|
||||
return src, true
|
||||
}
|
||||
|
||||
func (a *sourcesAPI) sourceError(w http.ResponseWriter, what string, err error) {
|
||||
switch {
|
||||
case errors.Is(err, storecontract.ErrSourcePathTaken):
|
||||
http.Error(w, "source path already taken", http.StatusConflict)
|
||||
case errors.Is(err, storecontract.ErrSourceSigningStale):
|
||||
http.Error(w, "source signing changed; reload and retry", http.StatusConflict)
|
||||
case errors.Is(err, storecontract.ErrSourceNotFound):
|
||||
http.Error(w, "source not found", http.StatusNotFound)
|
||||
case errors.Is(err, org.ErrInvalidWorkspace):
|
||||
http.Error(w, "that workspace is not one of this org's", http.StatusBadRequest)
|
||||
case errors.Is(err, storecontract.ErrSourceInUse):
|
||||
http.Error(w, "an armed binding fires on this source; pause or delete it first", http.StatusConflict)
|
||||
default:
|
||||
a.log.Error(what, "err", err)
|
||||
http.Error(w, what+" failed", http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
|
||||
)
|
||||
|
||||
// tasksAPI owns the /api/tasks routes and /api/task-meta. Optional
|
||||
// dependencies (steps, taskLogs, sandbox, chat) stay nil-safe: each handler
|
||||
// reports the feature unavailable rather than the module being absent.
|
||||
type tasksAPI struct {
|
||||
store storecontract.TaskStore
|
||||
steps storecontract.StepReader
|
||||
taskLogs TaskLogSource
|
||||
sandbox SandboxView
|
||||
chat *ChatService
|
||||
log *slog.Logger
|
||||
|
||||
authorize func(http.ResponseWriter, *http.Request) bool
|
||||
configSource func() ConfigViewSource
|
||||
recovery func(*http.Request, *task.Task) *taskRecoveryView
|
||||
}
|
||||
|
||||
func newTasksAPI(s *Server) *tasksAPI {
|
||||
return &tasksAPI{
|
||||
store: s.Store,
|
||||
steps: s.Steps,
|
||||
taskLogs: s.TaskLogs,
|
||||
sandbox: s.SandboxView,
|
||||
chat: s.Chat,
|
||||
log: s.Log,
|
||||
authorize: s.authorizeTaskMutation,
|
||||
configSource: s.configSource,
|
||||
recovery: s.taskRecovery,
|
||||
}
|
||||
}
|
||||
|
||||
func (a *tasksAPI) logf(msg string, args ...any) { warnf(a.log, msg, args...) }
|
||||
|
||||
// warnf logs at warn level and tolerates a nil logger, as tests construct
|
||||
// servers without one.
|
||||
func warnf(log *slog.Logger, msg string, args ...any) {
|
||||
if log != nil {
|
||||
log.Warn(msg, args...)
|
||||
}
|
||||
}
|
||||
|
||||
func (a *tasksAPI) register(mux *http.ServeMux) {
|
||||
mux.HandleFunc("GET /api/tasks", a.handleTasks)
|
||||
mux.HandleFunc("GET /api/task-meta", a.handleTaskMeta)
|
||||
mux.HandleFunc("POST /api/tasks/{id}/action", a.handleTaskAction)
|
||||
mux.HandleFunc("GET /api/tasks/{id}", a.handleTask)
|
||||
mux.HandleFunc("GET /api/tasks/{id}/attempts", a.handleTaskAttempts)
|
||||
mux.HandleFunc("GET /api/tasks/{id}/changes", a.handleTaskChanges)
|
||||
mux.HandleFunc("GET /api/tasks/{id}/debug", a.handleTaskDebug)
|
||||
mux.HandleFunc("GET /api/tasks/{id}/logs", a.handleTaskLogs)
|
||||
mux.HandleFunc("GET /api/tasks/{id}/transcript", a.handleTaskTranscript)
|
||||
mux.HandleFunc("GET /api/tasks/{id}/sandbox", a.handleTaskSandbox)
|
||||
mux.HandleFunc("GET /api/tasks/{id}/logs/download", a.handleTaskLogDownload)
|
||||
}
|
||||
@@ -39,6 +39,10 @@ type taskAttemptsView struct {
|
||||
Inputs map[string]any `json:"inputs,omitempty"`
|
||||
Outputs map[string]any `json:"outputs,omitempty"`
|
||||
CalledBy int64 `json:"called_by,omitempty"`
|
||||
// HandedOffFrom and HandedOffTo are the linked runs of the same work
|
||||
// item before and after this one.
|
||||
HandedOffFrom int64 `json:"handed_off_from,omitempty"`
|
||||
HandedOffTo int64 `json:"handed_off_to,omitempty"`
|
||||
// Recovery links a parked task to the page that fixes its blocker,
|
||||
// present only when the viewer may act there.
|
||||
Recovery *taskRecoveryView `json:"recovery,omitempty"`
|
||||
@@ -86,19 +90,19 @@ type taskAgentView struct {
|
||||
|
||||
// handleTaskAttempts returns a task's attempts from its events, each with the
|
||||
// stages recorded as step executions.
|
||||
func (s *Server) handleTaskAttempts(w http.ResponseWriter, r *http.Request) {
|
||||
t, ok := s.taskByPathID(w, r)
|
||||
func (a *tasksAPI) handleTaskAttempts(w http.ResponseWriter, r *http.Request) {
|
||||
t, ok := a.taskByPathID(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
evs, err := s.Store.TaskEvents(r.Context(), t.ID)
|
||||
evs, err := a.store.TaskEvents(r.Context(), t.ID)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
var steps []task.StepExecution
|
||||
if s.Steps != nil {
|
||||
steps, err = s.Steps.ListSteps(r.Context(), t.ID, 0)
|
||||
if a.steps != nil {
|
||||
steps, err = a.steps.ListSteps(r.Context(), t.ID, 0)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
@@ -117,7 +121,9 @@ func (s *Server) handleTaskAttempts(w http.ResponseWriter, r *http.Request) {
|
||||
Inputs: t.Inputs,
|
||||
Outputs: t.Outputs,
|
||||
CalledBy: t.CallParentTaskID,
|
||||
Recovery: s.taskRecovery(r, t),
|
||||
HandedOffFrom: t.HandoffFromTaskID,
|
||||
HandedOffTo: t.HandoffToTaskID,
|
||||
Recovery: a.recovery(r, t),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -125,13 +131,13 @@ func (s *Server) handleTaskAttempts(w http.ResponseWriter, r *http.Request) {
|
||||
// request itself and reporting false when it cannot. An unknown task is 404
|
||||
// plain text -- TaskByID says "no such row" the same way it says "here is the
|
||||
// row", so the distinction is drawn here rather than leaked to the page.
|
||||
func (s *Server) taskByPathID(w http.ResponseWriter, r *http.Request) (*task.Task, bool) {
|
||||
func (a *tasksAPI) taskByPathID(w http.ResponseWriter, r *http.Request) (*task.Task, bool) {
|
||||
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
|
||||
if err != nil {
|
||||
http.Error(w, "bad id", http.StatusBadRequest)
|
||||
return nil, false
|
||||
}
|
||||
t, err := s.Store.TaskByID(r.Context(), id)
|
||||
t, err := a.store.TaskByID(r.Context(), id)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return nil, false
|
||||
@@ -145,8 +151,8 @@ func (s *Server) taskByPathID(w http.ResponseWriter, r *http.Request) (*task.Tas
|
||||
|
||||
// taskAttemptTarget resolves the task in {id} and the requested attempt,
|
||||
// defaulting to the current one.
|
||||
func (s *Server) taskAttemptTarget(w http.ResponseWriter, r *http.Request) (*task.Task, int, bool) {
|
||||
t, ok := s.taskByPathID(w, r)
|
||||
func (a *tasksAPI) taskAttemptTarget(w http.ResponseWriter, r *http.Request) (*task.Task, int, bool) {
|
||||
t, ok := a.taskByPathID(w, r)
|
||||
if !ok {
|
||||
return nil, 0, false
|
||||
}
|
||||
File renamed without changes.
@@ -100,12 +100,12 @@ func structKeys(t reflect.Type) map[string]struct{} {
|
||||
}
|
||||
|
||||
// handleTaskChanges serves the changed files one attempt produced.
|
||||
func (s *Server) handleTaskChanges(w http.ResponseWriter, r *http.Request) {
|
||||
t, attempt, ok := s.taskAttemptTarget(w, r)
|
||||
func (a *tasksAPI) handleTaskChanges(w http.ResponseWriter, r *http.Request) {
|
||||
t, attempt, ok := a.taskAttemptTarget(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
evs, err := s.Store.TaskEvents(r.Context(), t.ID)
|
||||
evs, err := a.store.TaskEvents(r.Context(), t.ID)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
@@ -116,7 +116,7 @@ func (s *Server) handleTaskChanges(w http.ResponseWriter, r *http.Request) {
|
||||
// re-derived: the capture's own owner/repo/pr decide the URL, so a capture
|
||||
// taken before the PR existed has no pull-request link instead of one
|
||||
// pointing at a later attempt's PR.
|
||||
forge := s.resolveForge(r.Context())
|
||||
forge := a.resolveForge(r.Context())
|
||||
for i := range captures {
|
||||
target := task.Task{
|
||||
Owner: captures[i].Owner, Repo: captures[i].Repo,
|
||||
@@ -18,12 +18,12 @@ type taskDebugView struct {
|
||||
|
||||
// handleTaskDebug serves the task's raw record together with its whole event
|
||||
// list, for whichever attempt the request names.
|
||||
func (s *Server) handleTaskDebug(w http.ResponseWriter, r *http.Request) {
|
||||
t, attempt, ok := s.taskAttemptTarget(w, r)
|
||||
func (a *tasksAPI) handleTaskDebug(w http.ResponseWriter, r *http.Request) {
|
||||
t, attempt, ok := a.taskAttemptTarget(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
evs, err := s.Store.TaskEvents(r.Context(), t.ID)
|
||||
evs, err := a.store.TaskEvents(r.Context(), t.ID)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
@@ -67,13 +67,13 @@ func needsAttentionStatuses() []string {
|
||||
// narrows it (needs_attention is the grouped filter), ?limit sizes it, and ?cursor
|
||||
// resumes after the previous page; a full page answers the next cursor in the
|
||||
// X-Next-Cursor header.
|
||||
func (s *Server) handleTasks(w http.ResponseWriter, r *http.Request) {
|
||||
func (a *tasksAPI) handleTasks(w http.ResponseWriter, r *http.Request) {
|
||||
page, err := taskPageFrom(r.URL.Query())
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
tasks, err := s.Store.TasksPage(r.Context(), page)
|
||||
tasks, err := a.store.TasksPage(r.Context(), page)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
@@ -82,11 +82,11 @@ func (s *Server) handleTasks(w http.ResponseWriter, r *http.Request) {
|
||||
last := tasks[len(tasks)-1]
|
||||
w.Header().Set("X-Next-Cursor", fmt.Sprintf("%d.%d", last.UpdatedAt.UnixNano(), last.ID))
|
||||
}
|
||||
forge := s.resolveForge(r.Context())
|
||||
forge := a.resolveForge(r.Context())
|
||||
views := make([]taskView, len(tasks))
|
||||
for i := range tasks {
|
||||
repoURL, issueURL, prURL := taskURLs(tasks[i], forge(tasks[i]))
|
||||
views[i] = taskView{Task: tasks[i], Actions: taskstate.Actions(tasks[i].Status), Approval: taskstate.ApprovalKind(tasks[i].Status, tasks[i].ReviewGate), RepoURL: repoURL, IssueURL: issueURL, PRURL: prURL, Recovery: s.taskRecovery(r, &tasks[i])}
|
||||
views[i] = taskView{Task: tasks[i], Actions: taskstate.Actions(tasks[i].Status), Approval: taskstate.ApprovalKind(tasks[i].Status, tasks[i].ReviewGate), RepoURL: repoURL, IssueURL: issueURL, PRURL: prURL, Recovery: a.recovery(r, &tasks[i])}
|
||||
}
|
||||
writeJSON(w, views)
|
||||
}
|
||||
@@ -144,9 +144,9 @@ type forgeCoordinates struct {
|
||||
// resolveForge returns a function mapping a task to the instance forge. A
|
||||
// multi-identity install withholds links: its tasks reach forges through
|
||||
// organisation connections this projection does not carry.
|
||||
func (s *Server) resolveForge(ctx context.Context) func(task.Task) forgeCoordinates {
|
||||
func (a *tasksAPI) resolveForge(ctx context.Context) func(task.Task) forgeCoordinates {
|
||||
unlinked := func(task.Task) forgeCoordinates { return forgeCoordinates{} }
|
||||
view, ok, err := s.configSource()(ctx)
|
||||
view, ok, err := a.configSource()(ctx)
|
||||
if err != nil || !ok || view.MultiIdentity {
|
||||
return unlinked
|
||||
}
|
||||
@@ -172,13 +172,13 @@ func taskURLs(task task.Task, forge forgeCoordinates) (repoURL, issueURL, prURL
|
||||
return repoURL, issueURL, prURL
|
||||
}
|
||||
|
||||
func (s *Server) handleTask(w http.ResponseWriter, r *http.Request) {
|
||||
func (a *tasksAPI) handleTask(w http.ResponseWriter, r *http.Request) {
|
||||
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
|
||||
if err != nil {
|
||||
http.Error(w, "bad id", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
evs, err := s.Store.TaskEvents(r.Context(), id)
|
||||
evs, err := a.store.TaskEvents(r.Context(), id)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
@@ -206,8 +206,8 @@ type taskActionRequest struct {
|
||||
CurrentDefinition bool `json:"current_definition"`
|
||||
}
|
||||
|
||||
func (s *Server) handleTaskAction(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.authorizeTaskMutation(w, r) {
|
||||
func (a *tasksAPI) handleTaskAction(w http.ResponseWriter, r *http.Request) {
|
||||
if !a.authorize(w, r) {
|
||||
return
|
||||
}
|
||||
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
|
||||
@@ -219,7 +219,7 @@ func (s *Server) handleTaskAction(w http.ResponseWriter, r *http.Request) {
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if err := s.applyOperatorTaskAction(r.Context(), id, action, res); err != nil {
|
||||
if err := a.applyOperatorTaskAction(r.Context(), id, action, res); err != nil {
|
||||
switch {
|
||||
case errors.Is(err, taskactions.ErrNotFound):
|
||||
http.Error(w, "task not found", http.StatusNotFound)
|
||||
@@ -229,7 +229,7 @@ func (s *Server) handleTaskAction(w http.ResponseWriter, r *http.Request) {
|
||||
case errors.Is(err, taskactions.ErrUnavailable):
|
||||
http.Error(w, err.Error(), http.StatusServiceUnavailable)
|
||||
default:
|
||||
s.logf("task action failed", "task", id, "err", err)
|
||||
a.logf("task action failed", "task", id, "err", err)
|
||||
http.Error(w, "task action failed", http.StatusInternalServerError)
|
||||
}
|
||||
return
|
||||
@@ -348,8 +348,8 @@ func validOrigin(u *url.URL, wantScheme, wantHost string) bool {
|
||||
}
|
||||
|
||||
// applyOperatorTaskAction sends an operator's task action to the Gateway.
|
||||
func (s *Server) applyOperatorTaskAction(ctx context.Context, id int64, action taskstate.Action, res taskactions.ActionPayload) error {
|
||||
if s.Chat == nil || s.Chat.Contract == nil {
|
||||
func (a *tasksAPI) applyOperatorTaskAction(ctx context.Context, id int64, action taskstate.Action, res taskactions.ActionPayload) error {
|
||||
if a.chat == nil || a.chat.Contract == nil {
|
||||
return fmt.Errorf("%w: no gateway contract is wired", taskactions.ErrUnavailable)
|
||||
}
|
||||
// The actor comes from the credential the middleware resolved and never from
|
||||
@@ -360,7 +360,7 @@ func (s *Server) applyOperatorTaskAction(ctx context.Context, id int64, action t
|
||||
if value, ok := ActingIdentity(ctx); ok {
|
||||
actor = taskactions.ActorFor(value)
|
||||
}
|
||||
_, err := s.Chat.Contract.ApplyOperatorTaskAction(ctx, actor, id, action, res)
|
||||
_, err := a.chat.Contract.ApplyOperatorTaskAction(ctx, actor, id, action, res)
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -14,12 +14,12 @@ import (
|
||||
|
||||
// handleTaskLogs serves one attempt's log history, defaulting to the current
|
||||
// attempt. No reader reports disabled; no log file reports found=false.
|
||||
func (s *Server) handleTaskLogs(w http.ResponseWriter, r *http.Request) {
|
||||
id, attempt, ok := s.taskLogTarget(w, r)
|
||||
func (a *tasksAPI) handleTaskLogs(w http.ResponseWriter, r *http.Request) {
|
||||
id, attempt, ok := a.taskLogTarget(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
reader := s.taskLogReader()
|
||||
reader := a.taskLogs
|
||||
if reader == nil {
|
||||
writeDisabledTaskLogs(w, attempt)
|
||||
return
|
||||
@@ -83,12 +83,12 @@ func (s *Server) handleTaskLogs(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
// handleTaskLogDownload serves one attempt's raw log as a download. No reader
|
||||
// answers 503.
|
||||
func (s *Server) handleTaskLogDownload(w http.ResponseWriter, r *http.Request) {
|
||||
id, attempt, ok := s.taskLogTarget(w, r)
|
||||
func (a *tasksAPI) handleTaskLogDownload(w http.ResponseWriter, r *http.Request) {
|
||||
id, attempt, ok := a.taskLogTarget(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
reader := s.taskLogReader()
|
||||
reader := a.taskLogs
|
||||
if reader == nil {
|
||||
http.Error(w, logging.ErrTaskLogsUnavailable.Error(), http.StatusServiceUnavailable)
|
||||
return
|
||||
@@ -114,7 +114,7 @@ func (s *Server) handleTaskLogDownload(w http.ResponseWriter, r *http.Request) {
|
||||
// Once a 200 and a body are on the wire there is no status left to
|
||||
// send, so a failure partway through is logged where an operator can
|
||||
// find it rather than silently truncating the file.
|
||||
s.logf("task log download failed", "task", id, "attempt", attempt, "err", err)
|
||||
a.logf("task log download failed", "task", id, "attempt", attempt, "err", err)
|
||||
return
|
||||
}
|
||||
if !found {
|
||||
@@ -125,8 +125,8 @@ func (s *Server) handleTaskLogDownload(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
// taskLogTarget resolves the task and attempt for a log read, answering the
|
||||
// request itself on failure.
|
||||
func (s *Server) taskLogTarget(w http.ResponseWriter, r *http.Request) (id int64, attempt int, ok bool) {
|
||||
t, attempt, ok := s.taskAttemptTarget(w, r)
|
||||
func (a *tasksAPI) taskLogTarget(w http.ResponseWriter, r *http.Request) (id int64, attempt int, ok bool) {
|
||||
t, attempt, ok := a.taskAttemptTarget(w, r)
|
||||
if !ok {
|
||||
return 0, 0, false
|
||||
}
|
||||
@@ -206,14 +206,6 @@ func taskLogFilename(taskID int64, attempt int) string {
|
||||
return "task-" + strconv.FormatInt(taskID, 10) + "-attempt-" + strconv.Itoa(attempt) + ".log"
|
||||
}
|
||||
|
||||
// taskLogReader returns this process's task-log reader, or nil.
|
||||
func (s *Server) taskLogReader() TaskLogSource {
|
||||
if s == nil {
|
||||
return nil
|
||||
}
|
||||
return s.TaskLogs
|
||||
}
|
||||
|
||||
// TaskLogSource is the read seam the task-log handlers consume. It is the
|
||||
// logging package's own reader contract, so a registry and a remote client
|
||||
// satisfy it without either one restating the log format -- the package that
|
||||
@@ -47,6 +47,6 @@ func buildTaskMeta() taskMetaView {
|
||||
}
|
||||
|
||||
// handleTaskMeta serves the catalog. See buildTaskMeta for what it carries.
|
||||
func (s *Server) handleTaskMeta(w http.ResponseWriter, _ *http.Request) {
|
||||
func (a *tasksAPI) handleTaskMeta(w http.ResponseWriter, _ *http.Request) {
|
||||
writeJSON(w, buildTaskMeta())
|
||||
}
|
||||
@@ -24,8 +24,8 @@ type SandboxView interface {
|
||||
// handleTaskSandbox streams a running attempt's sandbox output to a WebSocket.
|
||||
// Reading it is the same authority as reading the task's log, decided before
|
||||
// this handler runs. Input from the browser is discarded: a view has no stdin.
|
||||
func (s *Server) handleTaskSandbox(w http.ResponseWriter, r *http.Request) {
|
||||
if s.SandboxView == nil {
|
||||
func (a *tasksAPI) handleTaskSandbox(w http.ResponseWriter, r *http.Request) {
|
||||
if a.sandbox == nil {
|
||||
http.Error(w, "sandbox view not configured", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
@@ -33,7 +33,7 @@ func (s *Server) handleTaskSandbox(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, "websocket upgrade required", http.StatusUpgradeRequired)
|
||||
return
|
||||
}
|
||||
t, attempt, ok := s.taskAttemptTarget(w, r)
|
||||
t, attempt, ok := a.taskAttemptTarget(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
@@ -46,9 +46,9 @@ func (s *Server) handleTaskSandbox(w http.ResponseWriter, r *http.Request) {
|
||||
ctx, cancel := context.WithCancel(ws.Request().Context())
|
||||
defer cancel()
|
||||
go func() { _, _ = io.Copy(io.Discard, ws); cancel() }()
|
||||
view, err := s.SandboxView.OpenRun(ctx, string(org.OrgFromContext(ws.Request().Context())), t.ID, int64(attempt))
|
||||
view, err := a.sandbox.OpenRun(ctx, string(org.OrgFromContext(ws.Request().Context())), t.ID, int64(attempt))
|
||||
if err != nil {
|
||||
s.logf("open sandbox view", "err", err, "task", t.ID, "attempt", attempt)
|
||||
a.logf("open sandbox view", "err", err, "task", t.ID, "attempt", attempt)
|
||||
_, _ = io.WriteString(ws, sandboxRefusal(err))
|
||||
return
|
||||
}
|
||||
Loaded 100 of 380 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user