mirror of
https://github.com/mountain-loop/yaak.git
synced 2026-12-02 21:14:15 +01:00
Compare commits
21
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
11e71b4b96 | ||
|
|
7c660f4528 | ||
|
|
0337ef35c9 | ||
|
|
602bd1bb45 | ||
|
|
57ab349901 | ||
|
|
7a6d275fdb | ||
|
|
7d0926c961 | ||
|
|
522b898620 | ||
|
|
cb7ed9264d | ||
|
|
90cb578e26 | ||
|
|
ff7eebf3cd | ||
|
|
eff0c06cb0 | ||
|
|
c6e09a5af3 | ||
|
|
b05071ef4b | ||
|
|
a44f31eeb2 | ||
|
|
1103d05915 | ||
|
|
2f5639a26f | ||
|
|
7f8b7bf567 | ||
|
|
096e83a7bd | ||
|
|
89ce84cefe | ||
|
|
d5d2a64c32 |
No files matched your search
@@ -0,0 +1,34 @@
|
|||||||
|
version: 2
|
||||||
|
|
||||||
|
updates:
|
||||||
|
- package-ecosystem: npm
|
||||||
|
directory: /
|
||||||
|
schedule:
|
||||||
|
interval: weekly
|
||||||
|
day: monday
|
||||||
|
open-pull-requests-limit: 5
|
||||||
|
groups:
|
||||||
|
npm-production:
|
||||||
|
dependency-type: production
|
||||||
|
update-types:
|
||||||
|
- minor
|
||||||
|
- patch
|
||||||
|
npm-development:
|
||||||
|
dependency-type: development
|
||||||
|
update-types:
|
||||||
|
- minor
|
||||||
|
- patch
|
||||||
|
|
||||||
|
- package-ecosystem: cargo
|
||||||
|
directory: /
|
||||||
|
schedule:
|
||||||
|
interval: weekly
|
||||||
|
day: monday
|
||||||
|
open-pull-requests-limit: 5
|
||||||
|
groups:
|
||||||
|
cargo:
|
||||||
|
patterns:
|
||||||
|
- "*"
|
||||||
|
update-types:
|
||||||
|
- minor
|
||||||
|
- patch
|
||||||
Generated
+52
-28
@@ -960,15 +960,6 @@ dependencies = [
|
|||||||
"serde",
|
"serde",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "bzip2"
|
|
||||||
version = "0.5.2"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "49ecfb22d906f800d4fe833b6282cf4dc1c298f5057ca0b5445e5c209735ca47"
|
|
||||||
dependencies = [
|
|
||||||
"bzip2-sys",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "bzip2"
|
name = "bzip2"
|
||||||
version = "0.6.1"
|
version = "0.6.1"
|
||||||
@@ -978,16 +969,6 @@ dependencies = [
|
|||||||
"libbz2-rs-sys",
|
"libbz2-rs-sys",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "bzip2-sys"
|
|
||||||
version = "0.1.13+1.0.8"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "225bff33b2141874fe80d71e07d6eec4f85c5c216453dd96388240f96e1acc14"
|
|
||||||
dependencies = [
|
|
||||||
"cc",
|
|
||||||
"pkg-config",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "cairo-rs"
|
name = "cairo-rs"
|
||||||
version = "0.18.5"
|
version = "0.18.5"
|
||||||
@@ -2114,7 +2095,7 @@ version = "2.3.2"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "c169adf067a787e1f1c58ed62906a557de85388bee4b54fb878b722ff606b113"
|
checksum = "c169adf067a787e1f1c58ed62906a557de85388bee4b54fb878b722ff606b113"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"bzip2 0.6.1",
|
"bzip2",
|
||||||
"clap",
|
"clap",
|
||||||
"fs-err",
|
"fs-err",
|
||||||
"indicatif",
|
"indicatif",
|
||||||
@@ -2914,11 +2895,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||||||
checksum = "26145e563e54f2cadc477553f1ec5ee650b00862f0a58bcd12cbdc5f0ea2d2f4"
|
checksum = "26145e563e54f2cadc477553f1ec5ee650b00862f0a58bcd12cbdc5f0ea2d2f4"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"cfg-if",
|
"cfg-if",
|
||||||
"js-sys",
|
|
||||||
"libc",
|
"libc",
|
||||||
"r-efi",
|
"r-efi",
|
||||||
"wasi 0.14.2+wasi-0.2.4",
|
"wasi 0.14.2+wasi-0.2.4",
|
||||||
"wasm-bindgen",
|
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -4194,6 +4173,15 @@ dependencies = [
|
|||||||
"value-bag",
|
"value-bag",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "lzma-rust2"
|
||||||
|
version = "0.15.8"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "e20f57f9918e5bd7bc58c22cdd70a6afc7375d4dd9683af5f2b34bd3d2bba619"
|
||||||
|
dependencies = [
|
||||||
|
"sha2",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "mac"
|
name = "mac"
|
||||||
version = "0.1.1"
|
version = "0.1.1"
|
||||||
@@ -6174,6 +6162,12 @@ version = "0.2.0"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391"
|
checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "ppmd-rust"
|
||||||
|
version = "1.4.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "9e9219bcb9d7aca6b2f63c83cf100cf78bcd619ac46e6ecbd0dd90869a39345d"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "ppv-lite86"
|
name = "ppv-lite86"
|
||||||
version = "0.2.21"
|
version = "0.2.21"
|
||||||
@@ -8906,7 +8900,7 @@ dependencies = [
|
|||||||
"tokio",
|
"tokio",
|
||||||
"url",
|
"url",
|
||||||
"windows-sys 0.60.2",
|
"windows-sys 0.60.2",
|
||||||
"zip",
|
"zip 4.6.1",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -11228,6 +11222,7 @@ dependencies = [
|
|||||||
"md5 0.8.0",
|
"md5 0.8.0",
|
||||||
"rusqlite",
|
"rusqlite",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
|
"sha2",
|
||||||
"tempfile",
|
"tempfile",
|
||||||
"thiserror 2.0.17",
|
"thiserror 2.0.17",
|
||||||
"tokio",
|
"tokio",
|
||||||
@@ -11375,7 +11370,7 @@ dependencies = [
|
|||||||
"yaak-models",
|
"yaak-models",
|
||||||
"yaak-plugins",
|
"yaak-plugins",
|
||||||
"yaak-templates",
|
"yaak-templates",
|
||||||
"zip",
|
"zip 7.0.0",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -12045,13 +12040,13 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "zip"
|
name = "zip"
|
||||||
version = "4.0.0"
|
version = "4.6.1"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "153a6fff49d264c4babdcfa6b4d534747f520e56e8f0f384f3b808c4b64cc1fd"
|
checksum = "caa8cd6af31c3b31c6631b8f483848b91589021b28fffe50adada48d4f4d2ed1"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"aes",
|
"aes",
|
||||||
"arbitrary",
|
"arbitrary",
|
||||||
"bzip2 0.5.2",
|
"bzip2",
|
||||||
"constant_time_eq 0.3.1",
|
"constant_time_eq 0.3.1",
|
||||||
"crc32fast",
|
"crc32fast",
|
||||||
"deflate64",
|
"deflate64",
|
||||||
@@ -12062,6 +12057,35 @@ dependencies = [
|
|||||||
"liblzma",
|
"liblzma",
|
||||||
"memchr",
|
"memchr",
|
||||||
"pbkdf2",
|
"pbkdf2",
|
||||||
|
"ppmd-rust",
|
||||||
|
"sha1",
|
||||||
|
"time",
|
||||||
|
"zeroize",
|
||||||
|
"zopfli",
|
||||||
|
"zstd",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "zip"
|
||||||
|
version = "7.0.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "bdd8a47718a4ee5fe78e07667cd36f3de80e7c2bfe727c7074245ffc7303c037"
|
||||||
|
dependencies = [
|
||||||
|
"aes",
|
||||||
|
"arbitrary",
|
||||||
|
"bzip2",
|
||||||
|
"constant_time_eq 0.3.1",
|
||||||
|
"crc32fast",
|
||||||
|
"deflate64",
|
||||||
|
"flate2",
|
||||||
|
"generic-array",
|
||||||
|
"getrandom 0.3.3",
|
||||||
|
"hmac",
|
||||||
|
"indexmap 2.14.0",
|
||||||
|
"lzma-rust2",
|
||||||
|
"memchr",
|
||||||
|
"pbkdf2",
|
||||||
|
"ppmd-rust",
|
||||||
"sha1",
|
"sha1",
|
||||||
"time",
|
"time",
|
||||||
"zeroize",
|
"zeroize",
|
||||||
@@ -12077,7 +12101,7 @@ checksum = "aed5f10c571472911e37d8f7601a8dfba52b4f7f73a344015291b82ab292faf6"
|
|||||||
dependencies = [
|
dependencies = [
|
||||||
"log 0.4.29",
|
"log 0.4.29",
|
||||||
"thiserror 2.0.17",
|
"thiserror 2.0.17",
|
||||||
"zip",
|
"zip 4.6.1",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
|
|||||||
@@ -17,7 +17,7 @@
|
|||||||
<br>
|
<br>
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<!-- sponsors-premium --><a href="https://github.com/MVST-Solutions"><img src="https://github.com/MVST-Solutions.png" width="80px" alt="User avatar: MVST-Solutions" /></a> <a href="https://github.com/dharsanb"><img src="https://github.com/dharsanb.png" width="80px" alt="User avatar: dharsanb" /></a> <a href="https://github.com/railwayapp"><img src="https://github.com/railwayapp.png" width="80px" alt="User avatar: railwayapp" /></a> <a href="https://github.com/caseyamcl"><img src="https://github.com/caseyamcl.png" width="80px" alt="User avatar: caseyamcl" /></a> <a href="https://github.com/bytebase"><img src="https://github.com/bytebase.png" width="80px" alt="User avatar: bytebase" /></a> <a href="https://github.com/"><img src="https://raw.githubusercontent.com/JamesIves/github-sponsors-readme-action/dev/.github/assets/placeholder.png" width="80px" alt="User avatar: " /></a> <!-- sponsors-premium -->
|
<!-- sponsors-premium --><a href="https://github.com/MVST-Solutions"><img src="https://github.com/MVST-Solutions.png" width="80px" alt="User avatar: MVST-Solutions" /></a> <a href="https://github.com/dharsanb"><img src="https://github.com/dharsanb.png" width="80px" alt="User avatar: dharsanb" /></a> <a href="https://github.com/railwayapp"><img src="https://github.com/railwayapp.png" width="80px" alt="User avatar: railwayapp" /></a> <a href="https://github.com/caseyamcl"><img src="https://github.com/caseyamcl.png" width="80px" alt="User avatar: caseyamcl" /></a> <a href="https://github.com/bytebase"><img src="https://github.com/bytebase.png" width="80px" alt="User avatar: bytebase" /></a> <a href="https://github.com/rauchg"><img src="https://github.com/rauchg.png" width="80px" alt="User avatar: rauchg" /></a> <a href="https://github.com/"><img src="https://raw.githubusercontent.com/JamesIves/github-sponsors-readme-action/dev/.github/assets/placeholder.png" width="80px" alt="User avatar: " /></a> <!-- sponsors-premium -->
|
||||||
</p>
|
</p>
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<!-- sponsors-base --><a href="https://github.com/seanwash"><img src="https://github.com/seanwash.png" width="50px" alt="User avatar: seanwash" /></a> <a href="https://github.com/jerath"><img src="https://github.com/jerath.png" width="50px" alt="User avatar: jerath" /></a> <a href="https://github.com/itsa-sh"><img src="https://github.com/itsa-sh.png" width="50px" alt="User avatar: itsa-sh" /></a> <a href="https://github.com/dmmulroy"><img src="https://github.com/dmmulroy.png" width="50px" alt="User avatar: dmmulroy" /></a> <a href="https://github.com/timcole"><img src="https://github.com/timcole.png" width="50px" alt="User avatar: timcole" /></a> <a href="https://github.com/VLZH"><img src="https://github.com/VLZH.png" width="50px" alt="User avatar: VLZH" /></a> <a href="https://github.com/terasaka2k"><img src="https://github.com/terasaka2k.png" width="50px" alt="User avatar: terasaka2k" /></a> <a href="https://github.com/andriyor"><img src="https://github.com/andriyor.png" width="50px" alt="User avatar: andriyor" /></a> <a href="https://github.com/majudhu"><img src="https://github.com/majudhu.png" width="50px" alt="User avatar: majudhu" /></a> <a href="https://github.com/axelrindle"><img src="https://github.com/axelrindle.png" width="50px" alt="User avatar: axelrindle" /></a> <a href="https://github.com/jirizverina"><img src="https://github.com/jirizverina.png" width="50px" alt="User avatar: jirizverina" /></a> <a href="https://github.com/chip-well"><img src="https://github.com/chip-well.png" width="50px" alt="User avatar: chip-well" /></a> <a href="https://github.com/GRAYAH"><img src="https://github.com/GRAYAH.png" width="50px" alt="User avatar: GRAYAH" /></a> <a href="https://github.com/flashblaze"><img src="https://github.com/flashblaze.png" width="50px" alt="User avatar: flashblaze" /></a> <a href="https://github.com/Frostist"><img src="https://github.com/Frostist.png" width="50px" alt="User avatar: Frostist" /></a> <a href="https://github.com/PurplProto"><img src="https://github.com/PurplProto.png" width="50px" alt="User avatar: PurplProto" /></a> <!-- sponsors-base -->
|
<!-- sponsors-base --><a href="https://github.com/seanwash"><img src="https://github.com/seanwash.png" width="50px" alt="User avatar: seanwash" /></a> <a href="https://github.com/jerath"><img src="https://github.com/jerath.png" width="50px" alt="User avatar: jerath" /></a> <a href="https://github.com/itsa-sh"><img src="https://github.com/itsa-sh.png" width="50px" alt="User avatar: itsa-sh" /></a> <a href="https://github.com/dmmulroy"><img src="https://github.com/dmmulroy.png" width="50px" alt="User avatar: dmmulroy" /></a> <a href="https://github.com/timcole"><img src="https://github.com/timcole.png" width="50px" alt="User avatar: timcole" /></a> <a href="https://github.com/VLZH"><img src="https://github.com/VLZH.png" width="50px" alt="User avatar: VLZH" /></a> <a href="https://github.com/terasaka2k"><img src="https://github.com/terasaka2k.png" width="50px" alt="User avatar: terasaka2k" /></a> <a href="https://github.com/andriyor"><img src="https://github.com/andriyor.png" width="50px" alt="User avatar: andriyor" /></a> <a href="https://github.com/majudhu"><img src="https://github.com/majudhu.png" width="50px" alt="User avatar: majudhu" /></a> <a href="https://github.com/axelrindle"><img src="https://github.com/axelrindle.png" width="50px" alt="User avatar: axelrindle" /></a> <a href="https://github.com/jirizverina"><img src="https://github.com/jirizverina.png" width="50px" alt="User avatar: jirizverina" /></a> <a href="https://github.com/chip-well"><img src="https://github.com/chip-well.png" width="50px" alt="User avatar: chip-well" /></a> <a href="https://github.com/GRAYAH"><img src="https://github.com/GRAYAH.png" width="50px" alt="User avatar: GRAYAH" /></a> <a href="https://github.com/flashblaze"><img src="https://github.com/flashblaze.png" width="50px" alt="User avatar: flashblaze" /></a> <a href="https://github.com/Frostist"><img src="https://github.com/Frostist.png" width="50px" alt="User avatar: Frostist" /></a> <a href="https://github.com/PurplProto"><img src="https://github.com/PurplProto.png" width="50px" alt="User avatar: PurplProto" /></a> <!-- sponsors-base -->
|
||||||
@@ -25,6 +25,10 @@
|
|||||||
|
|
||||||

|

|
||||||
|
|
||||||
|
## Install
|
||||||
|
|
||||||
|
Download Yaak for macOS, Windows, or Linux from [yaak.app/download](https://yaak.app/download). Package managers and other install methods are in the [installation docs](https://yaak.app/docs/getting-started/installation).
|
||||||
|
|
||||||
## Features
|
## Features
|
||||||
|
|
||||||
Yaak is an offline-first API client designed to stay out of your way while giving you everything you need when you need it.
|
Yaak is an offline-first API client designed to stay out of your way while giving you everything you need when you need it.
|
||||||
@@ -68,3 +72,9 @@ Built with [Tauri](https://tauri.app), Rust, and React, it’s fast, lightweight
|
|||||||
- [Yaak vs Postman](https://yaak.app/alternatives/postman)
|
- [Yaak vs Postman](https://yaak.app/alternatives/postman)
|
||||||
- [Yaak vs Bruno](https://yaak.app/alternatives/bruno)
|
- [Yaak vs Bruno](https://yaak.app/alternatives/bruno)
|
||||||
- [Yaak vs Insomnia](https://yaak.app/alternatives/insomnia)
|
- [Yaak vs Insomnia](https://yaak.app/alternatives/insomnia)
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
The source is [MIT licensed](LICENSE) and can be built and run for free, for both personal and commercial use.
|
||||||
|
|
||||||
|
The prebuilt binaries follow Yaak's [pricing terms](https://yaak.app/pricing): free for personal use, license required for commercial use.
|
||||||
@@ -1,10 +1,16 @@
|
|||||||
import type { WorkspaceSettingsTab } from "../components/WorkspaceSettingsDialog";
|
import type {
|
||||||
|
WorkspaceSettingsHighlight,
|
||||||
|
WorkspaceSettingsTab,
|
||||||
|
} from "../components/WorkspaceSettingsDialog";
|
||||||
import { WorkspaceSettingsDialog } from "../components/WorkspaceSettingsDialog";
|
import { WorkspaceSettingsDialog } from "../components/WorkspaceSettingsDialog";
|
||||||
import { activeWorkspaceIdAtom } from "../hooks/useActiveWorkspace";
|
import { activeWorkspaceIdAtom } from "../hooks/useActiveWorkspace";
|
||||||
import { jotaiStore } from "../lib/jotai";
|
import { jotaiStore } from "../lib/jotai";
|
||||||
|
|
||||||
export function openWorkspaceSettings(tab?: WorkspaceSettingsTab) {
|
export function openWorkspaceSettings(
|
||||||
|
tab?: WorkspaceSettingsTab,
|
||||||
|
highlight?: WorkspaceSettingsHighlight,
|
||||||
|
) {
|
||||||
const workspaceId = jotaiStore.get(activeWorkspaceIdAtom);
|
const workspaceId = jotaiStore.get(activeWorkspaceIdAtom);
|
||||||
if (workspaceId == null) return;
|
if (workspaceId == null) return;
|
||||||
WorkspaceSettingsDialog.show(workspaceId, tab);
|
WorkspaceSettingsDialog.show(workspaceId, tab, highlight);
|
||||||
}
|
}
|
||||||
@@ -31,6 +31,7 @@ import type { Pair } from "./core/PairEditor";
|
|||||||
import { PairEditor } from "./core/PairEditor";
|
import { PairEditor } from "./core/PairEditor";
|
||||||
import { PlainInput } from "./core/PlainInput";
|
import { PlainInput } from "./core/PlainInput";
|
||||||
import { Select } from "./core/Select";
|
import { Select } from "./core/Select";
|
||||||
|
import { SecretVariableHint } from "./hints/SecretVariableHint";
|
||||||
import { Markdown } from "./Markdown";
|
import { Markdown } from "./Markdown";
|
||||||
import { SelectFile } from "./SelectFile";
|
import { SelectFile } from "./SelectFile";
|
||||||
|
|
||||||
@@ -46,6 +47,8 @@ interface Props<T> {
|
|||||||
stateKey: string;
|
stateKey: string;
|
||||||
className?: string;
|
className?: string;
|
||||||
disabled?: boolean;
|
disabled?: boolean;
|
||||||
|
/** Offer to move literal secrets typed into password fields into a variable */
|
||||||
|
suggestVariables?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function DynamicForm<T extends Record<string, JsonPrimitive>>({
|
export function DynamicForm<T extends Record<string, JsonPrimitive>>({
|
||||||
@@ -57,6 +60,7 @@ export function DynamicForm<T extends Record<string, JsonPrimitive>>({
|
|||||||
stateKey,
|
stateKey,
|
||||||
className,
|
className,
|
||||||
disabled,
|
disabled,
|
||||||
|
suggestVariables,
|
||||||
}: Props<T>) {
|
}: Props<T>) {
|
||||||
const setDataAttr = useCallback(
|
const setDataAttr = useCallback(
|
||||||
(name: string, value: JsonPrimitive) => {
|
(name: string, value: JsonPrimitive) => {
|
||||||
@@ -73,6 +77,7 @@ export function DynamicForm<T extends Record<string, JsonPrimitive>>({
|
|||||||
stateKey={stateKey}
|
stateKey={stateKey}
|
||||||
autocompleteFunctions={autocompleteFunctions}
|
autocompleteFunctions={autocompleteFunctions}
|
||||||
autocompleteVariables={autocompleteVariables}
|
autocompleteVariables={autocompleteVariables}
|
||||||
|
suggestVariables={suggestVariables}
|
||||||
data={data}
|
data={data}
|
||||||
className={classNames(className, "pb-4")} // Pad the bottom to look nice
|
className={classNames(className, "pb-4")} // Pad the bottom to look nice
|
||||||
/>
|
/>
|
||||||
@@ -103,6 +108,7 @@ type FormInputsProps<T> = Pick<
|
|||||||
> & {
|
> & {
|
||||||
setDataAttr: (name: string, value: JsonPrimitive) => void;
|
setDataAttr: (name: string, value: JsonPrimitive) => void;
|
||||||
disabled?: boolean;
|
disabled?: boolean;
|
||||||
|
suggestVariables?: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
function FormInputs<T extends Record<string, JsonPrimitive>>({
|
function FormInputs<T extends Record<string, JsonPrimitive>>({
|
||||||
@@ -113,6 +119,7 @@ function FormInputs<T extends Record<string, JsonPrimitive>>({
|
|||||||
setDataAttr,
|
setDataAttr,
|
||||||
data,
|
data,
|
||||||
disabled,
|
disabled,
|
||||||
|
suggestVariables,
|
||||||
}: FormInputsProps<T>) {
|
}: FormInputsProps<T>) {
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
@@ -147,6 +154,7 @@ function FormInputs<T extends Record<string, JsonPrimitive>>({
|
|||||||
arg={input}
|
arg={input}
|
||||||
autocompleteFunctions={autocompleteFunctions || false}
|
autocompleteFunctions={autocompleteFunctions || false}
|
||||||
autocompleteVariables={autocompleteVariables || false}
|
autocompleteVariables={autocompleteVariables || false}
|
||||||
|
suggestVariables={suggestVariables || false}
|
||||||
onChange={(v) => setDataAttr(input.name, v)}
|
onChange={(v) => setDataAttr(input.name, v)}
|
||||||
value={
|
value={
|
||||||
data[input.name] != null ? String(data[input.name]) : (input.defaultValue ?? "")
|
data[input.name] != null ? String(data[input.name]) : (input.defaultValue ?? "")
|
||||||
@@ -287,6 +295,7 @@ function TextArg({
|
|||||||
value,
|
value,
|
||||||
autocompleteFunctions,
|
autocompleteFunctions,
|
||||||
autocompleteVariables,
|
autocompleteVariables,
|
||||||
|
suggestVariables,
|
||||||
stateKey,
|
stateKey,
|
||||||
}: {
|
}: {
|
||||||
arg: FormInputText;
|
arg: FormInputText;
|
||||||
@@ -294,6 +303,7 @@ function TextArg({
|
|||||||
onChange: (v: string) => void;
|
onChange: (v: string) => void;
|
||||||
autocompleteFunctions: boolean;
|
autocompleteFunctions: boolean;
|
||||||
autocompleteVariables: boolean;
|
autocompleteVariables: boolean;
|
||||||
|
suggestVariables: boolean;
|
||||||
stateKey: string;
|
stateKey: string;
|
||||||
}) {
|
}) {
|
||||||
const props: InputProps = {
|
const props: InputProps = {
|
||||||
@@ -316,10 +326,19 @@ function TextArg({
|
|||||||
autocompleteFunctions,
|
autocompleteFunctions,
|
||||||
autocompleteVariables,
|
autocompleteVariables,
|
||||||
};
|
};
|
||||||
if (autocompleteVariables || autocompleteFunctions || arg.completionOptions) {
|
const input =
|
||||||
return <Input {...props} />;
|
autocompleteVariables || autocompleteFunctions || arg.completionOptions ? (
|
||||||
}
|
<Input {...props} />
|
||||||
return <PlainInput {...props} />;
|
) : (
|
||||||
|
<PlainInput {...props} />
|
||||||
|
);
|
||||||
|
if (!suggestVariables || !arg.password) return input;
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col gap-2">
|
||||||
|
{input}
|
||||||
|
<SecretVariableHint name={arg.name} value={value} onReplace={onChange} />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function EditorArg({
|
function EditorArg({
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ import {
|
|||||||
withEncryptionEnabled,
|
withEncryptionEnabled,
|
||||||
} from "../lib/setupOrConfigureEncryption";
|
} from "../lib/setupOrConfigureEncryption";
|
||||||
import { DismissibleBanner } from "./core/DismissibleBanner";
|
import { DismissibleBanner } from "./core/DismissibleBanner";
|
||||||
|
import { FeatureHint } from "./core/FeatureHint";
|
||||||
import type { GenericCompletionConfig } from "./core/Editor/genericCompletion";
|
import type { GenericCompletionConfig } from "./core/Editor/genericCompletion";
|
||||||
import type { PairEditorHandle, PairWithId } from "./core/PairEditor";
|
import type { PairEditorHandle, PairWithId } from "./core/PairEditor";
|
||||||
import { ensurePairId } from "./core/PairEditor.util";
|
import { ensurePairId } from "./core/PairEditor.util";
|
||||||
@@ -152,6 +153,17 @@ export function EnvironmentEditor({ environment, hideName, className, setRef }:
|
|||||||
This sharable environment contains plain-text secrets
|
This sharable environment contains plain-text secrets
|
||||||
</DismissibleBanner>
|
</DismissibleBanner>
|
||||||
)}
|
)}
|
||||||
|
{!environment.public && !isEncryptionEnabled && hasSecretLookingVariable(environment) && (
|
||||||
|
<FeatureHint
|
||||||
|
id="encrypt-secrets"
|
||||||
|
className="mr-3"
|
||||||
|
docsUrl="https://yaak.app/docs/collaboration/secrets-encryption"
|
||||||
|
action={{ label: "Enable Encryption", onClick: setupOrConfigureEncryption }}
|
||||||
|
>
|
||||||
|
Some of these look like secrets. Encrypt them so the workspace is safe to sync to a
|
||||||
|
folder or share with a team.
|
||||||
|
</FeatureHint>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
<PairOrBulkEditor
|
<PairOrBulkEditor
|
||||||
setRef={setRef}
|
setRef={setRef}
|
||||||
@@ -173,3 +185,9 @@ export function EnvironmentEditor({ environment, hideName, className, setRef }:
|
|||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const SECRET_NAME = /token|secret|password|passwd|api[_-]?key|private[_-]?key|credential/i;
|
||||||
|
|
||||||
|
function hasSecretLookingVariable(environment: Environment) {
|
||||||
|
return environment.variables.some((v) => v.value.trim() !== "" && SECRET_NAME.test(v.name));
|
||||||
|
}
|
||||||
@@ -133,6 +133,8 @@ export function GrpcRequestPane({
|
|||||||
onSend({ message: activeRequest.message });
|
onSend({ message: activeRequest.message });
|
||||||
}, [activeRequest, onSend]);
|
}, [activeRequest, onSend]);
|
||||||
|
|
||||||
|
const hasDescription = activeRequest.description.trim().length > 0;
|
||||||
|
|
||||||
const tabs: TabItem[] = useMemo(
|
const tabs: TabItem[] = useMemo(
|
||||||
() => [
|
() => [
|
||||||
{ value: TAB_MESSAGE, label: "Message" },
|
{ value: TAB_MESSAGE, label: "Message" },
|
||||||
@@ -146,10 +148,10 @@ export function GrpcRequestPane({
|
|||||||
{
|
{
|
||||||
value: TAB_DESCRIPTION,
|
value: TAB_DESCRIPTION,
|
||||||
label: "Info",
|
label: "Info",
|
||||||
rightSlot: activeRequest.description && <CountBadge count={true} />,
|
rightSlot: hasDescription && <CountBadge count={true} />,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
[activeRequest.description, authTab, metadataTab, numSettingsOverrides],
|
[authTab, hasDescription, metadataTab, numSettingsOverrides],
|
||||||
);
|
);
|
||||||
|
|
||||||
const handleMetadataChange = useCallback(
|
const handleMetadataChange = useCallback(
|
||||||
|
|||||||
@@ -178,6 +178,7 @@ export function HttpAuthenticationEditor({ model }: Props) {
|
|||||||
disabled={model.authentication.disabled === true}
|
disabled={model.authentication.disabled === true}
|
||||||
autocompleteVariables
|
autocompleteVariables
|
||||||
autocompleteFunctions
|
autocompleteFunctions
|
||||||
|
suggestVariables
|
||||||
stateKey={`auth.${model.id}.${model.authenticationType}`}
|
stateKey={`auth.${model.id}.${model.authenticationType}`}
|
||||||
inputs={authConfig.data?.args ?? []}
|
inputs={authConfig.data?.args ?? []}
|
||||||
data={model.authentication}
|
data={model.authentication}
|
||||||
|
|||||||
@@ -52,6 +52,7 @@ import { JsonBodyEditor } from "./JsonBodyEditor";
|
|||||||
import { MarkdownEditor } from "./MarkdownEditor";
|
import { MarkdownEditor } from "./MarkdownEditor";
|
||||||
import { RequestMethodDropdown } from "./RequestMethodDropdown";
|
import { RequestMethodDropdown } from "./RequestMethodDropdown";
|
||||||
import { countOverriddenSettings, ModelSettingsEditor } from "./ModelSettingsEditor";
|
import { countOverriddenSettings, ModelSettingsEditor } from "./ModelSettingsEditor";
|
||||||
|
import { SharedOriginHint } from "./hints/SharedOriginHint";
|
||||||
import { UrlBar } from "./UrlBar";
|
import { UrlBar } from "./UrlBar";
|
||||||
import { UrlParametersEditor } from "./UrlParameterEditor";
|
import { UrlParametersEditor } from "./UrlParameterEditor";
|
||||||
|
|
||||||
@@ -165,6 +166,8 @@ export function HttpRequestPane({ style, fullHeight, className, activeRequest }:
|
|||||||
: 0;
|
: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const hasDescription = activeRequest.description.trim().length > 0;
|
||||||
|
|
||||||
const tabs = useMemo<TabItem[]>(
|
const tabs = useMemo<TabItem[]>(
|
||||||
() => [
|
() => [
|
||||||
{
|
{
|
||||||
@@ -260,6 +263,7 @@ export function HttpRequestPane({ style, fullHeight, className, activeRequest }:
|
|||||||
{
|
{
|
||||||
value: TAB_DESCRIPTION,
|
value: TAB_DESCRIPTION,
|
||||||
label: "Info",
|
label: "Info",
|
||||||
|
rightSlot: hasDescription && <CountBadge count={true} />,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
[
|
[
|
||||||
@@ -267,6 +271,7 @@ export function HttpRequestPane({ style, fullHeight, className, activeRequest }:
|
|||||||
authTab,
|
authTab,
|
||||||
contentType,
|
contentType,
|
||||||
handleContentTypeChange,
|
handleContentTypeChange,
|
||||||
|
hasDescription,
|
||||||
headersTab,
|
headersTab,
|
||||||
numParams,
|
numParams,
|
||||||
numSettingsOverrides,
|
numSettingsOverrides,
|
||||||
@@ -340,24 +345,27 @@ export function HttpRequestPane({ style, fullHeight, className, activeRequest }:
|
|||||||
>
|
>
|
||||||
{activeRequest && (
|
{activeRequest && (
|
||||||
<>
|
<>
|
||||||
<UrlBar
|
<div>
|
||||||
stateKey={`url.${activeRequest.id}`}
|
<UrlBar
|
||||||
key={forceUpdateKey + urlKey}
|
stateKey={`url.${activeRequest.id}`}
|
||||||
url={activeRequest.url}
|
key={forceUpdateKey + urlKey}
|
||||||
placeholder="https://example.com"
|
url={activeRequest.url}
|
||||||
onPasteOverwrite={handlePaste}
|
placeholder="https://example.com"
|
||||||
autocomplete={autocomplete}
|
onPasteOverwrite={handlePaste}
|
||||||
onSend={handleSend}
|
autocomplete={autocomplete}
|
||||||
onCancel={cancelResponse}
|
onSend={handleSend}
|
||||||
onUrlChange={handleUrlChange}
|
onCancel={cancelResponse}
|
||||||
leftSlot={
|
onUrlChange={handleUrlChange}
|
||||||
<div className="py-0.5">
|
leftSlot={
|
||||||
<RequestMethodDropdown request={activeRequest} className="ml-0.5 h-full!" />
|
<div className="py-0.5">
|
||||||
</div>
|
<RequestMethodDropdown request={activeRequest} className="ml-0.5 h-full!" />
|
||||||
}
|
</div>
|
||||||
forceUpdateKey={updateKey}
|
}
|
||||||
isLoading={activeResponse != null && activeResponse.state !== "closed"}
|
forceUpdateKey={updateKey}
|
||||||
/>
|
isLoading={activeResponse != null && activeResponse.state !== "closed"}
|
||||||
|
/>
|
||||||
|
<SharedOriginHint />
|
||||||
|
</div>
|
||||||
<Tabs
|
<Tabs
|
||||||
ref={tabsRef}
|
ref={tabsRef}
|
||||||
label="Request"
|
label="Request"
|
||||||
|
|||||||
@@ -28,6 +28,7 @@ import { TabContent, Tabs } from "./core/Tabs/Tabs";
|
|||||||
import { Tooltip } from "./core/Tooltip";
|
import { Tooltip } from "./core/Tooltip";
|
||||||
import { EmptyStateText } from "./EmptyStateText";
|
import { EmptyStateText } from "./EmptyStateText";
|
||||||
import { ErrorBoundary } from "./ErrorBoundary";
|
import { ErrorBoundary } from "./ErrorBoundary";
|
||||||
|
import { ChainingHint } from "./hints/ChainingHint";
|
||||||
import { HttpResponseTimeline } from "./HttpResponseTimeline";
|
import { HttpResponseTimeline } from "./HttpResponseTimeline";
|
||||||
import { RecentHttpResponsesDropdown } from "./RecentHttpResponsesDropdown";
|
import { RecentHttpResponsesDropdown } from "./RecentHttpResponsesDropdown";
|
||||||
import { RequestBodyViewer } from "./RequestBodyViewer";
|
import { RequestBodyViewer } from "./RequestBodyViewer";
|
||||||
@@ -280,6 +281,7 @@ export function HttpResponsePane({ style, className, activeRequestId }: Props) {
|
|||||||
{activeResponse.error}
|
{activeResponse.error}
|
||||||
</Banner>
|
</Banner>
|
||||||
)}
|
)}
|
||||||
|
{activeResponse && <ChainingHint response={activeResponse} mimeType={mimeType} />}
|
||||||
{/* Show tabs if we have any data (headers, body, etc.) even if there's an error */}
|
{/* Show tabs if we have any data (headers, body, etc.) even if there's an error */}
|
||||||
<Tabs
|
<Tabs
|
||||||
tabs={tabs}
|
tabs={tabs}
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import {
|
|||||||
type ImportSource,
|
type ImportSource,
|
||||||
type Workspace,
|
type Workspace,
|
||||||
} from "@yaakapp-internal/models";
|
} from "@yaakapp-internal/models";
|
||||||
import { HStack, Icon, InlineCode, VStack } from "@yaakapp-internal/ui";
|
import { Banner, HStack, Icon, type IconProps, InlineCode, VStack } from "@yaakapp-internal/ui";
|
||||||
import { platform } from "@yaakapp-internal/platform";
|
import { platform } from "@yaakapp-internal/platform";
|
||||||
import classNames from "classnames";
|
import classNames from "classnames";
|
||||||
import { formatDistanceToNowStrict } from "date-fns";
|
import { formatDistanceToNowStrict } from "date-fns";
|
||||||
@@ -260,14 +260,17 @@ function LoadedImportDataDialog({
|
|||||||
|
|
||||||
const itemTree = useMemo(() => buildItemTree(items), [items]);
|
const itemTree = useMemo(() => buildItemTree(items), [items]);
|
||||||
|
|
||||||
// A folder row's checkbox aggregates its subtree the way the git commit tree does: creates and
|
// A folder row's checkbox carries everything beneath it, deletions included — the row labels
|
||||||
// updates toggle together, while removals only ever cascade beneath a removed folder.
|
// say which of those are destructive. Checking anything also brings back the folders it needs
|
||||||
const toggleNode = (node: CheckboxTreeNode<ImportPlanItem>, checked: boolean) => {
|
// to live in.
|
||||||
const targets = new Set(
|
const toggleNode = (node: CheckboxTreeNode<TreeRow>, checked: boolean) => {
|
||||||
collectItems(node)
|
const targets = new Set(togglableItems(node).map((i) => i.modelId));
|
||||||
.filter((i) => togglesWith(node.data, i))
|
if (checked && node.data.kind === "item") {
|
||||||
.map((i) => i.modelId),
|
const byId = new Map(items.map((i) => [i.modelId, i]));
|
||||||
);
|
for (const ancestor of ancestorsOf(node.data.item, byId)) {
|
||||||
|
if (isMissingFolder(ancestor)) targets.add(ancestor.modelId);
|
||||||
|
}
|
||||||
|
}
|
||||||
setItems((prev) => prev.map((i) => (targets.has(i.modelId) ? { ...i, selected: checked } : i)));
|
setItems((prev) => prev.map((i) => (targets.has(i.modelId) ? { ...i, selected: checked } : i)));
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -277,25 +280,16 @@ function LoadedImportDataDialog({
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
// A row the user can't meaningfully toggle on its own: a planned resource inside a deselected
|
// Deleting a folder takes its contents with it, so those rows have nothing left to decide.
|
||||||
// new folder can't exist, and a removed folder takes its contents with it.
|
|
||||||
const disabledIds = useMemo(() => {
|
const disabledIds = useMemo(() => {
|
||||||
const disabled = new Set<string>();
|
const disabled = new Set<string>();
|
||||||
const byId = new Map(items.map((i) => [i.modelId, i]));
|
const byId = new Map(items.map((i) => [i.modelId, i]));
|
||||||
for (const item of items) {
|
for (const item of items) {
|
||||||
const seen = new Set<string>();
|
if (item.action !== "delete") continue;
|
||||||
let parentId = item.parentId;
|
for (const parent of ancestorsOf(item, byId)) {
|
||||||
while (parentId != null && !seen.has(parentId)) {
|
if (parent.action === "delete" && parent.selected) {
|
||||||
seen.add(parentId);
|
|
||||||
const parent = byId.get(parentId);
|
|
||||||
if (parent == null || parent.model !== "folder") break;
|
|
||||||
if (parent.action === "create" && !parent.selected && item.action !== "delete") {
|
|
||||||
disabled.add(item.modelId);
|
disabled.add(item.modelId);
|
||||||
}
|
}
|
||||||
if (parent.action === "delete" && parent.selected && item.action === "delete") {
|
|
||||||
disabled.add(item.modelId);
|
|
||||||
}
|
|
||||||
parentId = parent.parentId;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return disabled;
|
return disabled;
|
||||||
@@ -314,18 +308,26 @@ function LoadedImportDataDialog({
|
|||||||
return item.selected;
|
return item.selected;
|
||||||
}).length;
|
}).length;
|
||||||
|
|
||||||
const destinationLabel = (() => {
|
// The row's label carries what kind of destination it is, so the value can just be its name
|
||||||
if (plan.destination.type === "new_workspace") return "New workspace";
|
const [destinationLabel, destinationValue] = ((): [string, string] => {
|
||||||
|
if (plan.destination.type === "new_workspace") {
|
||||||
|
const names = plan.resources.workspaces.map((w) => w.name).filter((n) => n !== "");
|
||||||
|
if (names.length === 0) return ["New workspace", "Untitled"];
|
||||||
|
return [pluralize("New workspace", names.length), names.join(", ")];
|
||||||
|
}
|
||||||
const { workspaceId, folderId } = plan.destination;
|
const { workspaceId, folderId } = plan.destination;
|
||||||
const name = workspaces.find((w) => w.id === workspaceId)?.name ?? "Unknown workspace";
|
const name = workspaces.find((w) => w.id === workspaceId)?.name ?? "Unknown workspace";
|
||||||
return folderId != null && folderId === selectedFolder?.id
|
return [
|
||||||
? `${name} / ${selectedFolder.name}`
|
"Destination",
|
||||||
: name;
|
folderId != null && folderId === selectedFolder?.id
|
||||||
|
? `${name} / ${selectedFolder.name}`
|
||||||
|
: name,
|
||||||
|
];
|
||||||
})();
|
})();
|
||||||
|
|
||||||
// The destination workspace roots the tree. It is not a plan item — commit always applies
|
// The destination workspace roots the tree. It is not a plan item — commit always applies
|
||||||
// it — so its checkbox only aggregates the subtree.
|
// it — so its checkbox only aggregates the subtree.
|
||||||
const workspaceRoot: CheckboxTreeNode<ImportPlanItem> = (() => {
|
const workspaceRoot: CheckboxTreeNode<TreeRow> = (() => {
|
||||||
const planned = plan.resources.workspaces[0];
|
const planned = plan.resources.workspaces[0];
|
||||||
const planDestination = plan.destination;
|
const planDestination = plan.destination;
|
||||||
const existing =
|
const existing =
|
||||||
@@ -335,11 +337,9 @@ function LoadedImportDataDialog({
|
|||||||
return {
|
return {
|
||||||
key: existing?.id ?? planned?.id ?? "workspace",
|
key: existing?.id ?? planned?.id ?? "workspace",
|
||||||
data: {
|
data: {
|
||||||
action: plan.destination.type === "new_workspace" ? "create" : "unchanged",
|
kind: "destination",
|
||||||
model: "workspace",
|
label: existing?.name ?? planned?.name ?? "New workspace",
|
||||||
modelId: existing?.id ?? planned?.id ?? "workspace",
|
isNew: planDestination.type === "new_workspace",
|
||||||
name: existing?.name ?? planned?.name ?? "New workspace",
|
|
||||||
selected: true,
|
|
||||||
},
|
},
|
||||||
children: itemTree,
|
children: itemTree,
|
||||||
};
|
};
|
||||||
@@ -349,40 +349,42 @@ function LoadedImportDataDialog({
|
|||||||
<VStack space={4} className="pb-4">
|
<VStack space={4} className="pb-4">
|
||||||
<div className="rounded-lg border border-border-subtle divide-y divide-border-subtle">
|
<div className="rounded-lg border border-border-subtle divide-y divide-border-subtle">
|
||||||
<PreviewRow label="Detected format" value={plan.importer} />
|
<PreviewRow label="Detected format" value={plan.importer} />
|
||||||
<PreviewRow label="Destination" value={destinationLabel} />
|
<PreviewRow label={destinationLabel} value={destinationValue} />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{plan.warnings.map((warning) => (
|
||||||
|
<Banner
|
||||||
|
key={`${warning.title}:${warning.detail}`}
|
||||||
|
color={warning.level === "warning" ? "warning" : "info"}
|
||||||
|
className="flex items-start gap-2.5"
|
||||||
|
>
|
||||||
|
<Icon
|
||||||
|
icon={warning.level === "warning" ? "alert_triangle" : "info"}
|
||||||
|
size="sm"
|
||||||
|
className="mt-0.5"
|
||||||
|
/>
|
||||||
|
<div className="min-w-0">
|
||||||
|
<div className="text-sm font-medium">{warning.title}</div>
|
||||||
|
<div className="text-xs text-text-subtle mt-0.5">{warning.detail}</div>
|
||||||
|
</div>
|
||||||
|
</Banner>
|
||||||
|
))}
|
||||||
|
|
||||||
<div className="rounded-lg border border-border-subtle px-3 py-2 overflow-y-auto max-h-[40vh]">
|
<div className="rounded-lg border border-border-subtle px-3 py-2 overflow-y-auto max-h-[40vh]">
|
||||||
<CheckboxTree
|
<CheckboxTree
|
||||||
node={workspaceRoot}
|
node={workspaceRoot}
|
||||||
checked={nodeCheckedStatus}
|
checked={nodeCheckedStatus}
|
||||||
onCheck={toggleNode}
|
onCheck={toggleNode}
|
||||||
isCheckboxDisabled={(n) => disabledIds.has(n.key)}
|
isCheckboxDisabled={(n) => disabledIds.has(n.key)}
|
||||||
isRelevant={(n) => n.data.model === "workspace" || n.data.action !== "unchanged"}
|
isCollapsedByDefault={(n) => n.data.kind === "item" && n.data.item.action === "ignored"}
|
||||||
renderRow={(n) => <ImportTreeRow item={n.data} onResolveConflict={resolveConflict} />}
|
isRelevant={(n) =>
|
||||||
|
n.data.kind === "destination" ||
|
||||||
|
(n.data.kind === "item" && n.data.item.action !== "unchanged")
|
||||||
|
}
|
||||||
|
renderRow={(n) => <ImportTreeRow row={n.data} onResolveConflict={resolveConflict} />}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{plan.warnings.length > 0 && (
|
|
||||||
<div>
|
|
||||||
<div className="text-sm font-semibold mb-1">Import details</div>
|
|
||||||
<div className="rounded-lg border border-border-subtle divide-y divide-border-subtle">
|
|
||||||
{plan.warnings.map((warning) => (
|
|
||||||
<div
|
|
||||||
key={`${warning.title}:${warning.detail}`}
|
|
||||||
className="flex items-start gap-2.5 px-3 py-2.5"
|
|
||||||
>
|
|
||||||
<Icon icon="info" color="info" size="sm" className="mt-0.5" />
|
|
||||||
<div className="min-w-0">
|
|
||||||
<div className="text-sm font-medium">{warning.title}</div>
|
|
||||||
<div className="text-xs text-text-subtle mt-0.5">{warning.detail}</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<HStack space={2} alignItems="center" className="mt-3">
|
<HStack space={2} alignItems="center" className="mt-3">
|
||||||
{footerNote !== "" && <div className="text-xs text-text-subtle">{footerNote}</div>}
|
{footerNote !== "" && <div className="text-xs text-text-subtle">{footerNote}</div>}
|
||||||
<Button
|
<Button
|
||||||
@@ -402,7 +404,7 @@ function LoadedImportDataDialog({
|
|||||||
? "Importing"
|
? "Importing"
|
||||||
: changeCount > 0
|
: changeCount > 0
|
||||||
? `Apply ${changeCount} ${changeCount === 1 ? "Change" : "Changes"}`
|
? `Apply ${changeCount} ${changeCount === 1 ? "Change" : "Changes"}`
|
||||||
: "Apply"}
|
: "Done"}
|
||||||
</Button>
|
</Button>
|
||||||
</HStack>
|
</HStack>
|
||||||
</VStack>
|
</VStack>
|
||||||
@@ -545,31 +547,42 @@ function LoadedImportDataDialog({
|
|||||||
}
|
}
|
||||||
|
|
||||||
function ImportTreeRow({
|
function ImportTreeRow({
|
||||||
item,
|
row,
|
||||||
onResolveConflict,
|
onResolveConflict,
|
||||||
}: {
|
}: {
|
||||||
item: ImportPlanItem;
|
row: TreeRow;
|
||||||
onResolveConflict: (modelId: string, resolution: "keep_mine" | "take_source") => void;
|
onResolveConflict: (modelId: string, resolution: "keep_mine" | "take_source") => void;
|
||||||
}) {
|
}) {
|
||||||
|
if (row.kind !== "item") {
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Icon color="secondary" icon={row.kind === "destination" ? "house" : row.icon} />
|
||||||
|
<div className="truncate flex-1">{row.label}</div>
|
||||||
|
{row.kind === "destination" && row.isNew && (
|
||||||
|
<ActionChip label="new" help="Created by this import" className="text-success" />
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const { item } = row;
|
||||||
|
const label = actionLabel(item);
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
{item.model === "workspace" || item.model === "folder" || item.model === "environment" ? (
|
{item.model === "folder" || item.model === "environment" ? (
|
||||||
<Icon
|
<Icon color="secondary" icon={item.model === "folder" ? "folder" : "variable"} />
|
||||||
color="secondary"
|
|
||||||
icon={
|
|
||||||
item.model === "workspace" ? "house" : item.model === "folder" ? "folder" : "variable"
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
) : (
|
) : (
|
||||||
<span aria-hidden className="w-4" />
|
<span aria-hidden className="w-4" />
|
||||||
)}
|
)}
|
||||||
<div className="truncate flex-1">{item.name}</div>
|
<div className="truncate flex-1">{item.name}</div>
|
||||||
{item.action === "conflict" ? (
|
{item.action === "conflict" ? (
|
||||||
<div className="shrink-0 flex items-center gap-1.5">
|
<div className="shrink-0">
|
||||||
<SegmentedControl
|
<SegmentedControl
|
||||||
name={`conflict-${item.modelId}`}
|
name={`conflict-${item.modelId}`}
|
||||||
label={`Resolve conflict for ${item.name}`}
|
label={`Resolve conflict for ${item.name}`}
|
||||||
hideLabel
|
hideLabel
|
||||||
|
size="2xs"
|
||||||
|
help={actionHelp(item)}
|
||||||
value={item.resolution ?? "keep_mine"}
|
value={item.resolution ?? "keep_mine"}
|
||||||
onChange={(v) => onResolveConflict(item.modelId, v)}
|
onChange={(v) => onResolveConflict(item.modelId, v)}
|
||||||
options={[
|
options={[
|
||||||
@@ -577,29 +590,49 @@ function ImportTreeRow({
|
|||||||
{ value: "take_source", label: "Take source" },
|
{ value: "take_source", label: "Take source" },
|
||||||
]}
|
]}
|
||||||
/>
|
/>
|
||||||
<IconTooltip content={actionHelp(item)} iconSize="sm" />
|
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
actionLabel(item) && (
|
label != null && (
|
||||||
<InlineCode
|
<ActionChip
|
||||||
|
label={label}
|
||||||
|
help={actionHelp(item)}
|
||||||
className={classNames(
|
className={classNames(
|
||||||
"py-0 bg-transparent w-32 shrink-0 whitespace-nowrap text-xs",
|
|
||||||
"inline-flex items-center justify-center gap-1.5",
|
|
||||||
item.action === "create" && "text-success",
|
item.action === "create" && "text-success",
|
||||||
item.action === "update" && "text-info",
|
item.action === "update" && "text-info",
|
||||||
item.action === "delete" && "text-danger",
|
item.action === "delete" && "text-danger",
|
||||||
item.action === "keep_local" && item.selected && "text-warning",
|
item.action === "keep_local" && item.selected && "text-warning",
|
||||||
|
item.action === "ignored" && "text-text-subtlest",
|
||||||
)}
|
)}
|
||||||
>
|
/>
|
||||||
{actionLabel(item)}
|
|
||||||
<IconTooltip content={actionHelp(item)} iconSize="xs" />
|
|
||||||
</InlineCode>
|
|
||||||
)
|
)
|
||||||
)}
|
)}
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function ActionChip({
|
||||||
|
label,
|
||||||
|
help,
|
||||||
|
className,
|
||||||
|
}: {
|
||||||
|
label: string;
|
||||||
|
help: string | null;
|
||||||
|
className?: string;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<InlineCode
|
||||||
|
className={classNames(
|
||||||
|
"py-0 bg-transparent w-32 shrink-0 whitespace-nowrap text-xs",
|
||||||
|
"inline-flex items-center justify-center gap-1.5",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{label}
|
||||||
|
{help != null && <IconTooltip content={help} iconSize="xs" />}
|
||||||
|
</InlineCode>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
function actionLabel(item: ImportPlanItem): string | null {
|
function actionLabel(item: ImportPlanItem): string | null {
|
||||||
switch (item.action) {
|
switch (item.action) {
|
||||||
case "create":
|
case "create":
|
||||||
@@ -610,29 +643,68 @@ function actionLabel(item: ImportPlanItem): string | null {
|
|||||||
return "removed";
|
return "removed";
|
||||||
case "keep_local":
|
case "keep_local":
|
||||||
return "edited";
|
return "edited";
|
||||||
|
case "ignored":
|
||||||
|
return "ignored";
|
||||||
default:
|
default:
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function actionHelp(item: ImportPlanItem): string | null {
|
function actionHelp(item: ImportPlanItem): string | null {
|
||||||
|
const help = (text: string) =>
|
||||||
|
item.changedFields.length > 0
|
||||||
|
? `${text} · ${item.changedFields.map(fieldLabel).join(", ")}`
|
||||||
|
: text;
|
||||||
switch (item.action) {
|
switch (item.action) {
|
||||||
case "create":
|
case "create":
|
||||||
return "Added since the last import";
|
return "Not in this workspace yet";
|
||||||
case "update":
|
case "update":
|
||||||
return "Changed since the last import";
|
return item.reason === "moved_into_ignored_folder"
|
||||||
|
? "Moved into a folder that isn't imported. Importing that folder brings it along"
|
||||||
|
: help("Changed in the source since the last import");
|
||||||
case "delete":
|
case "delete":
|
||||||
return "Deleted since the last import";
|
return "Gone from the source since the last import. Checking it deletes it here";
|
||||||
case "keep_local":
|
case "keep_local":
|
||||||
return "Local edits made since the last import. Importing will revert them if checked";
|
return help("Changed here since the last import. Checking it reverts to the source");
|
||||||
case "conflict":
|
case "conflict":
|
||||||
return "Changed both here and in the file since the last import";
|
return help("Changed here and in the source since the last import");
|
||||||
|
case "ignored":
|
||||||
|
return "Not in this workspace. Imports leave it alone until you check it";
|
||||||
default:
|
default:
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function buildItemTree(items: ImportPlanItem[]): CheckboxTreeNode<ImportPlanItem>[] {
|
function fieldLabel(field: string): string {
|
||||||
|
return field.replace(/([A-Z])/g, " $1").toLowerCase();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Every plan item above `item`, nearest first. */
|
||||||
|
function ancestorsOf(item: ImportPlanItem, byId: Map<string, ImportPlanItem>): ImportPlanItem[] {
|
||||||
|
const ancestors: ImportPlanItem[] = [];
|
||||||
|
const seen = new Set<string>();
|
||||||
|
let parentId = item.parentId;
|
||||||
|
while (parentId != null && !seen.has(parentId)) {
|
||||||
|
seen.add(parentId);
|
||||||
|
const parent = byId.get(parentId);
|
||||||
|
if (parent == null) break;
|
||||||
|
ancestors.push(parent);
|
||||||
|
parentId = parent.parentId;
|
||||||
|
}
|
||||||
|
return ancestors;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A row of the preview tree. Most are plan items, but the destination workspace and the group the
|
||||||
|
* workspace's environments sit in are headings: they aggregate their children and decide nothing
|
||||||
|
* themselves.
|
||||||
|
*/
|
||||||
|
type TreeRow =
|
||||||
|
| { kind: "destination"; label: string; isNew: boolean }
|
||||||
|
| { kind: "group"; label: string; icon: IconProps["icon"] }
|
||||||
|
| { kind: "item"; item: ImportPlanItem };
|
||||||
|
|
||||||
|
function buildItemTree(items: ImportPlanItem[]): CheckboxTreeNode<TreeRow>[] {
|
||||||
const byId = new Map(items.map((i) => [i.modelId, i]));
|
const byId = new Map(items.map((i) => [i.modelId, i]));
|
||||||
const childrenOf = new Map<string, ImportPlanItem[]>();
|
const childrenOf = new Map<string, ImportPlanItem[]>();
|
||||||
const roots: ImportPlanItem[] = [];
|
const roots: ImportPlanItem[] = [];
|
||||||
@@ -646,45 +718,66 @@ function buildItemTree(items: ImportPlanItem[]): CheckboxTreeNode<ImportPlanItem
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const foldersFirst = (list: ImportPlanItem[]) => [
|
const byKind = (list: ImportPlanItem[]) => [
|
||||||
|
...list.filter((i) => i.model === "environment"),
|
||||||
...list.filter((i) => i.model === "folder"),
|
...list.filter((i) => i.model === "folder"),
|
||||||
...list.filter((i) => i.model !== "folder"),
|
...list.filter((i) => i.model !== "environment" && i.model !== "folder"),
|
||||||
];
|
];
|
||||||
|
|
||||||
const toNode = (item: ImportPlanItem, seen: Set<string>): CheckboxTreeNode<ImportPlanItem> => ({
|
const toNode = (item: ImportPlanItem, seen: Set<string>): CheckboxTreeNode<TreeRow> => ({
|
||||||
key: item.modelId,
|
key: item.modelId,
|
||||||
data: item,
|
data: { kind: "item", item },
|
||||||
children: seen.has(item.modelId)
|
children: seen.has(item.modelId)
|
||||||
? []
|
? []
|
||||||
: foldersFirst(childrenOf.get(item.modelId) ?? []).map((c) =>
|
: byKind(childrenOf.get(item.modelId) ?? []).map((c) =>
|
||||||
toNode(c, new Set([...seen, item.modelId])),
|
toNode(c, new Set([...seen, item.modelId])),
|
||||||
),
|
),
|
||||||
});
|
});
|
||||||
|
|
||||||
return foldersFirst(roots).map((r) => toNode(r, new Set()));
|
// The workspace's environments have nothing to sit under — a sub-environment is a sibling of
|
||||||
|
// the base one, not its child — so a heading groups them into one thing to turn on and off.
|
||||||
|
const environments = roots.filter((i) => i.model === "environment");
|
||||||
|
const others = byKind(roots.filter((i) => i.model !== "environment"));
|
||||||
|
const nodes = others.map((r) => toNode(r, new Set()));
|
||||||
|
if (environments.length === 0) return nodes;
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
key: "group:environments",
|
||||||
|
data: { kind: "group", label: "Variables", icon: "variable" },
|
||||||
|
children: environments.map((e) => toNode(e, new Set())),
|
||||||
|
},
|
||||||
|
...nodes,
|
||||||
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
function collectItems(node: CheckboxTreeNode<ImportPlanItem>): ImportPlanItem[] {
|
function collectRows(node: CheckboxTreeNode<TreeRow>): TreeRow[] {
|
||||||
return [node.data, ...node.children.flatMap(collectItems)];
|
return [node.data, ...node.children.flatMap(collectRows)];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A folder that isn't there yet, so anything inside it needs it brought in first. */
|
||||||
|
function isMissingFolder(item: ImportPlanItem): boolean {
|
||||||
|
return item.model === "folder" && (item.action === "create" || item.action === "ignored");
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Whether toggling `root`'s checkbox also toggles `item` in its subtree. Destructive decisions
|
* The plan item a row's checkbox decides, if it decides one. An unchanged resource has nothing to
|
||||||
* (deletions, reverting local edits) never ride along with a parent toggle.
|
* decide and a conflict is decided by its own control, so neither takes a checkbox — nor rides
|
||||||
|
* along with a parent's.
|
||||||
*/
|
*/
|
||||||
function togglesWith(root: ImportPlanItem, item: ImportPlanItem): boolean {
|
function togglableItem(row: TreeRow): ImportPlanItem | null {
|
||||||
if (item.model === "workspace") return false;
|
if (row.kind !== "item") return null;
|
||||||
if (root.action === "delete") return item.action === "delete";
|
const { item } = row;
|
||||||
if (item.action === "keep_local") {
|
return item.action === "unchanged" || item.action === "conflict" ? null : item;
|
||||||
return root.modelId === item.modelId && item.model !== "folder";
|
|
||||||
}
|
|
||||||
return item.action === "create" || item.action === "update";
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function nodeCheckedStatus(
|
function togglableItems(node: CheckboxTreeNode<TreeRow>): ImportPlanItem[] {
|
||||||
node: CheckboxTreeNode<ImportPlanItem>,
|
return collectRows(node)
|
||||||
): boolean | "indeterminate" | "hidden" {
|
.map(togglableItem)
|
||||||
const covered = collectItems(node).filter((i) => togglesWith(node.data, i));
|
.filter((i) => i != null);
|
||||||
|
}
|
||||||
|
|
||||||
|
function nodeCheckedStatus(node: CheckboxTreeNode<TreeRow>): boolean | "indeterminate" | "hidden" {
|
||||||
|
const covered = togglableItems(node);
|
||||||
if (covered.length === 0) return "hidden";
|
if (covered.length === 0) return "hidden";
|
||||||
const selected = covered.filter((i) => i.selected).length;
|
const selected = covered.filter((i) => i.selected).length;
|
||||||
if (selected === covered.length) return true;
|
if (selected === covered.length) return true;
|
||||||
|
|||||||
@@ -59,6 +59,7 @@ export function SyncToFilesystemSetting({
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
<SettingRowDirectory
|
<SettingRowDirectory
|
||||||
|
highlightKey="sync_dir"
|
||||||
title="Local directory sync"
|
title="Local directory sync"
|
||||||
description="Sync data to a folder for backup and Git integration."
|
description="Sync data to a folder for backup and Git integration."
|
||||||
filePath={value.filePath}
|
filePath={value.filePath}
|
||||||
|
|||||||
@@ -110,6 +110,8 @@ export function WebsocketRequestPane({ style, fullHeight, className, activeReque
|
|||||||
[activeRequest.url, activeRequest.urlParameters, handleRenamePathPlaceholder],
|
[activeRequest.url, activeRequest.urlParameters, handleRenamePathPlaceholder],
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const hasDescription = activeRequest.description.trim().length > 0;
|
||||||
|
|
||||||
const tabs = useMemo<TabItem[]>(() => {
|
const tabs = useMemo<TabItem[]>(() => {
|
||||||
return [
|
return [
|
||||||
{
|
{
|
||||||
@@ -131,9 +133,10 @@ export function WebsocketRequestPane({ style, fullHeight, className, activeReque
|
|||||||
{
|
{
|
||||||
value: TAB_DESCRIPTION,
|
value: TAB_DESCRIPTION,
|
||||||
label: "Info",
|
label: "Info",
|
||||||
|
rightSlot: hasDescription && <CountBadge count={true} />,
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
}, [authTab, headersTab, numSettingsOverrides, urlParameterPairs.length]);
|
}, [authTab, hasDescription, headersTab, numSettingsOverrides, urlParameterPairs.length]);
|
||||||
|
|
||||||
const { activeResponse } = usePinnedHttpResponse(activeRequestId);
|
const { activeResponse } = usePinnedHttpResponse(activeRequestId);
|
||||||
const { mutate: cancelResponse } = useCancelHttpResponse(activeResponse?.id ?? null);
|
const { mutate: cancelResponse } = useCancelHttpResponse(activeResponse?.id ?? null);
|
||||||
|
|||||||
@@ -25,8 +25,12 @@ interface Props {
|
|||||||
workspaceId: string;
|
workspaceId: string;
|
||||||
hide: () => void;
|
hide: () => void;
|
||||||
tab?: WorkspaceSettingsTab;
|
tab?: WorkspaceSettingsTab;
|
||||||
|
highlight?: WorkspaceSettingsHighlight;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Settings rows that can be pointed out when the dialog opens */
|
||||||
|
export type WorkspaceSettingsHighlight = "sync_dir";
|
||||||
|
|
||||||
const TAB_AUTH = "auth";
|
const TAB_AUTH = "auth";
|
||||||
const TAB_DNS = "dns";
|
const TAB_DNS = "dns";
|
||||||
const TAB_HEADERS = "headers";
|
const TAB_HEADERS = "headers";
|
||||||
@@ -42,7 +46,7 @@ export type WorkspaceSettingsTab =
|
|||||||
|
|
||||||
const DEFAULT_TAB: WorkspaceSettingsTab = TAB_GENERAL;
|
const DEFAULT_TAB: WorkspaceSettingsTab = TAB_GENERAL;
|
||||||
|
|
||||||
export function WorkspaceSettingsDialog({ workspaceId, hide, tab }: Props) {
|
export function WorkspaceSettingsDialog({ workspaceId, hide, tab, highlight }: Props) {
|
||||||
const workspace = useAtomValue(workspacesAtom).find((w) => w.id === workspaceId);
|
const workspace = useAtomValue(workspacesAtom).find((w) => w.id === workspaceId);
|
||||||
const workspaceMeta = useAtomValue(workspaceMetasAtom).find((m) => m.workspaceId === workspaceId);
|
const workspaceMeta = useAtomValue(workspaceMetasAtom).find((m) => m.workspaceId === workspaceId);
|
||||||
const authTab = useAuthTab(TAB_AUTH, workspace ?? null);
|
const authTab = useAuthTab(TAB_AUTH, workspace ?? null);
|
||||||
@@ -104,7 +108,7 @@ export function WorkspaceSettingsDialog({ workspaceId, hide, tab }: Props) {
|
|||||||
/>
|
/>
|
||||||
</TabContent>
|
</TabContent>
|
||||||
<TabContent value={TAB_SETTINGS} className="overflow-y-auto h-full px-4">
|
<TabContent value={TAB_SETTINGS} className="overflow-y-auto h-full px-4">
|
||||||
<SettingsList className="space-y-8 pb-3">
|
<SettingsList className="space-y-8 pb-3" highlight={highlight}>
|
||||||
<SettingsSection title={null}>
|
<SettingsSection title={null}>
|
||||||
<SyncToFilesystemSetting
|
<SyncToFilesystemSetting
|
||||||
layout="settings"
|
layout="settings"
|
||||||
@@ -178,14 +182,23 @@ export function WorkspaceSettingsDialog({ workspaceId, hide, tab }: Props) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
WorkspaceSettingsDialog.show = (workspaceId: string, tab?: WorkspaceSettingsTab) => {
|
WorkspaceSettingsDialog.show = (
|
||||||
|
workspaceId: string,
|
||||||
|
tab?: WorkspaceSettingsTab,
|
||||||
|
highlight?: WorkspaceSettingsHighlight,
|
||||||
|
) => {
|
||||||
showDialog({
|
showDialog({
|
||||||
id: "workspace-settings",
|
id: "workspace-settings",
|
||||||
size: "lg",
|
size: "lg",
|
||||||
className: "h-[calc(100vh-5rem)] max-h-200!",
|
className: "h-[calc(100vh-5rem)] max-h-200!",
|
||||||
noPadding: true,
|
noPadding: true,
|
||||||
render: ({ hide }) => (
|
render: ({ hide }) => (
|
||||||
<WorkspaceSettingsDialog workspaceId={workspaceId} hide={hide} tab={tab} />
|
<WorkspaceSettingsDialog
|
||||||
|
workspaceId={workspaceId}
|
||||||
|
hide={hide}
|
||||||
|
tab={tab}
|
||||||
|
highlight={highlight}
|
||||||
|
/>
|
||||||
),
|
),
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
@@ -21,6 +21,8 @@ interface Props<T> {
|
|||||||
isCheckboxDisabled?: (node: CheckboxTreeNode<T>) => boolean;
|
isCheckboxDisabled?: (node: CheckboxTreeNode<T>) => boolean;
|
||||||
/** An irrelevant row is hidden unless one of its descendants is relevant */
|
/** An irrelevant row is hidden unless one of its descendants is relevant */
|
||||||
isRelevant: (node: CheckboxTreeNode<T>) => boolean;
|
isRelevant: (node: CheckboxTreeNode<T>) => boolean;
|
||||||
|
/** A node that starts collapsed, so a large subtree doesn't crowd out the rest */
|
||||||
|
isCollapsedByDefault?: (node: CheckboxTreeNode<T>) => boolean;
|
||||||
renderRow: (node: CheckboxTreeNode<T>) => ReactNode;
|
renderRow: (node: CheckboxTreeNode<T>) => ReactNode;
|
||||||
onSelectRow?: (node: CheckboxTreeNode<T>) => void;
|
onSelectRow?: (node: CheckboxTreeNode<T>) => void;
|
||||||
canSelectRow?: (node: CheckboxTreeNode<T>) => boolean;
|
canSelectRow?: (node: CheckboxTreeNode<T>) => boolean;
|
||||||
@@ -29,7 +31,9 @@ interface Props<T> {
|
|||||||
|
|
||||||
export function CheckboxTree<T>(props: Props<T>) {
|
export function CheckboxTree<T>(props: Props<T>) {
|
||||||
const { node, depth = 0 } = props;
|
const { node, depth = 0 } = props;
|
||||||
const [collapsed, setCollapsed] = useState<boolean>(false);
|
const [collapsed, setCollapsed] = useState<boolean>(
|
||||||
|
() => props.isCollapsedByDefault?.(node) ?? false,
|
||||||
|
);
|
||||||
if (!hasRelevantNode(node, props.isRelevant)) return null;
|
if (!hasRelevantNode(node, props.isRelevant)) return null;
|
||||||
|
|
||||||
const checked = props.checked(node);
|
const checked = props.checked(node);
|
||||||
|
|||||||
@@ -2,11 +2,12 @@ import type { Color } from "@yaakapp-internal/plugins";
|
|||||||
import type { BannerProps } from "@yaakapp-internal/ui";
|
import type { BannerProps } from "@yaakapp-internal/ui";
|
||||||
import { Banner } from "@yaakapp-internal/ui";
|
import { Banner } from "@yaakapp-internal/ui";
|
||||||
import classNames from "classnames";
|
import classNames from "classnames";
|
||||||
import type { MouseEvent } from "react";
|
import type { MouseEvent, ReactNode } from "react";
|
||||||
import { useEffect } from "react";
|
import { useEffect } from "react";
|
||||||
import { useKeyValue } from "../../hooks/useKeyValue";
|
import { useKeyValue } from "../../hooks/useKeyValue";
|
||||||
import type { ButtonProps } from "./Button";
|
import type { ButtonProps } from "./Button";
|
||||||
import { Button } from "./Button";
|
import { Button } from "./Button";
|
||||||
|
import { IconButton } from "./IconButton";
|
||||||
|
|
||||||
type DismissibleBannerSize = "sm" | "xs";
|
type DismissibleBannerSize = "sm" | "xs";
|
||||||
|
|
||||||
@@ -18,17 +19,21 @@ export function DismissibleBanner({
|
|||||||
onDismiss,
|
onDismiss,
|
||||||
onShow,
|
onShow,
|
||||||
actions,
|
actions,
|
||||||
|
variant = "banner",
|
||||||
...props
|
...props
|
||||||
}: BannerProps & {
|
}: BannerProps & {
|
||||||
id: string;
|
id: string;
|
||||||
size?: DismissibleBannerSize;
|
size?: DismissibleBannerSize;
|
||||||
onDismiss?: () => void | Promise<void>;
|
onDismiss?: () => void | Promise<void>;
|
||||||
onShow?: () => void | Promise<void>;
|
onShow?: () => void | Promise<void>;
|
||||||
|
/** A tip dismisses with an X in the corner instead of a text button */
|
||||||
|
variant?: "banner" | "tip";
|
||||||
actions?: {
|
actions?: {
|
||||||
label: string;
|
label: string;
|
||||||
onClick: () => void;
|
onClick: () => void;
|
||||||
color?: Color;
|
color?: Color;
|
||||||
variant?: ButtonProps["variant"];
|
variant?: ButtonProps["variant"];
|
||||||
|
rightSlot?: ReactNode;
|
||||||
}[];
|
}[];
|
||||||
}) {
|
}) {
|
||||||
const {
|
const {
|
||||||
@@ -56,54 +61,69 @@ export function DismissibleBanner({
|
|||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
event.stopPropagation();
|
event.stopPropagation();
|
||||||
};
|
};
|
||||||
|
const dismiss = (event: MouseEvent) => {
|
||||||
|
stopParentClick(event);
|
||||||
|
setDismissed(true).catch(console.error);
|
||||||
|
Promise.resolve(onDismiss?.()).catch(console.error);
|
||||||
|
};
|
||||||
|
const isTip = variant === "tip";
|
||||||
|
const hasActionRow = !isTip || (actions?.length ?? 0) > 0;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Banner
|
<Banner
|
||||||
className={classNames(
|
className={classNames(className, "relative", size === "xs" && "!px-2 !py-2 text-xs")}
|
||||||
className,
|
|
||||||
"relative",
|
|
||||||
size === "xs" && "!px-2 !py-2 text-xs",
|
|
||||||
)}
|
|
||||||
{...props}
|
{...props}
|
||||||
>
|
>
|
||||||
<div className="@container">
|
<div className={classNames("@container", isTip && "relative")}>
|
||||||
|
{isTip && (
|
||||||
|
<IconButton
|
||||||
|
icon="x"
|
||||||
|
size="2xs"
|
||||||
|
iconSize="sm"
|
||||||
|
title="Dismiss message"
|
||||||
|
className="absolute! -top-0.5 -right-1 @[34rem]:top-1/2 @[34rem]:-translate-y-1/2 opacity-50 hover:opacity-100"
|
||||||
|
onClick={dismiss}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
<div
|
<div
|
||||||
className={classNames(
|
className={classNames(
|
||||||
"grid @[34rem]:grid-cols-[minmax(0,1fr)_auto] @[34rem]:items-center",
|
"grid @[34rem]:grid-cols-[minmax(0,1fr)_auto] @[34rem]:items-center",
|
||||||
|
isTip && "@[34rem]:pr-5",
|
||||||
size === "xs" ? "gap-1.5 @[34rem]:gap-2" : "gap-2 @[34rem]:gap-3",
|
size === "xs" ? "gap-1.5 @[34rem]:gap-2" : "gap-2 @[34rem]:gap-3",
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
{children}
|
{isTip ? <div className="pr-5 @[34rem]:pr-0">{children}</div> : children}
|
||||||
<div className="flex flex-wrap gap-1.5 @[34rem]:justify-end">
|
{hasActionRow && (
|
||||||
<Button
|
<div className="flex flex-col gap-1.5 @[16rem]:flex-row @[16rem]:flex-wrap @[16rem]:justify-end">
|
||||||
variant="border"
|
{!isTip && (
|
||||||
color={props.color}
|
<Button
|
||||||
size={actionSize}
|
variant="border"
|
||||||
onClick={(event) => {
|
color={props.color}
|
||||||
stopParentClick(event);
|
size={actionSize}
|
||||||
setDismissed(true).catch(console.error);
|
onClick={dismiss}
|
||||||
Promise.resolve(onDismiss?.()).catch(console.error);
|
title="Dismiss message"
|
||||||
}}
|
>
|
||||||
title="Dismiss message"
|
Dismiss
|
||||||
>
|
</Button>
|
||||||
Dismiss
|
)}
|
||||||
</Button>
|
{actions?.map((a) => (
|
||||||
{actions?.map((a) => (
|
<Button
|
||||||
<Button
|
key={a.label}
|
||||||
key={a.label}
|
rightSlot={a.rightSlot}
|
||||||
variant={a.variant ?? "border"}
|
variant={a.variant ?? "border"}
|
||||||
color={a.color ?? props.color}
|
color={a.color ?? props.color}
|
||||||
size={actionSize}
|
size={actionSize}
|
||||||
onClick={(event) => {
|
onClick={(event) => {
|
||||||
stopParentClick(event);
|
stopParentClick(event);
|
||||||
a.onClick();
|
a.onClick();
|
||||||
}}
|
}}
|
||||||
title={a.label}
|
title={a.label}
|
||||||
>
|
>
|
||||||
{a.label}
|
{a.label}
|
||||||
</Button>
|
</Button>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</Banner>
|
</Banner>
|
||||||
|
|||||||
@@ -0,0 +1,78 @@
|
|||||||
|
import { platform } from "@yaakapp-internal/platform";
|
||||||
|
import { Icon } from "@yaakapp-internal/ui";
|
||||||
|
import type { ReactNode } from "react";
|
||||||
|
import { setKeyValue } from "../../lib/keyValueStore";
|
||||||
|
import { DismissibleBanner } from "./DismissibleBanner";
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
/** Stable id; the dismissal is remembered under it. */
|
||||||
|
id: string;
|
||||||
|
children: ReactNode;
|
||||||
|
docsUrl?: string;
|
||||||
|
action?: { label: string; onClick: () => void | Promise<void> };
|
||||||
|
onDismiss?: () => void;
|
||||||
|
className?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A one-time nudge toward a feature the user hasn't found yet. Dismissed once, gone for good.
|
||||||
|
*/
|
||||||
|
export function FeatureHint({ id, children, docsUrl, action, onDismiss, className }: Props) {
|
||||||
|
const actions = [
|
||||||
|
...(action ? [{ ...action, variant: "solid" as const, color: "info" as const }] : []),
|
||||||
|
...(action != null && docsUrl != null
|
||||||
|
? [
|
||||||
|
{
|
||||||
|
label: "Docs",
|
||||||
|
rightSlot: <Icon icon="external_link" size="xs" className="opacity-60" />,
|
||||||
|
onClick: () => platform.openUrl(docsUrl).catch(console.error),
|
||||||
|
},
|
||||||
|
]
|
||||||
|
: []),
|
||||||
|
];
|
||||||
|
return (
|
||||||
|
<DismissibleBanner
|
||||||
|
id={`feature-hint:${id}`}
|
||||||
|
variant="tip"
|
||||||
|
color="info"
|
||||||
|
size="xs"
|
||||||
|
onDismiss={onDismiss}
|
||||||
|
className={className}
|
||||||
|
actions={actions}
|
||||||
|
>
|
||||||
|
<div className="flex items-start gap-2 text-xs">
|
||||||
|
<Icon icon="sparkles" size="xs" className="hidden @[16rem]:block mt-0.5 shrink-0" />
|
||||||
|
<div className="min-w-0">
|
||||||
|
{children}
|
||||||
|
{action == null && docsUrl != null && (
|
||||||
|
<>
|
||||||
|
{" "}
|
||||||
|
(
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="group inline-flex items-center gap-0.5 underline hover:text-info cursor-pointer! [&_*]:cursor-pointer!"
|
||||||
|
onClick={() => platform.openUrl(docsUrl).catch(console.error)}
|
||||||
|
>
|
||||||
|
docs
|
||||||
|
<Icon
|
||||||
|
icon="external_link"
|
||||||
|
size="xs"
|
||||||
|
className="opacity-80 group-hover:opacity-100"
|
||||||
|
/>
|
||||||
|
</button>
|
||||||
|
)
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</DismissibleBanner>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function dismissFeatureHint(id: string) {
|
||||||
|
return setKeyValue({
|
||||||
|
namespace: "global",
|
||||||
|
key: ["dismiss-banner", `feature-hint:${id}`],
|
||||||
|
value: true,
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -205,6 +205,7 @@ export const PlainInput = forwardRef<{ focus: () => void }, PlainInputProps>(fun
|
|||||||
autoComplete="off"
|
autoComplete="off"
|
||||||
autoCapitalize="off"
|
autoCapitalize="off"
|
||||||
autoCorrect="off"
|
autoCorrect="off"
|
||||||
|
writingsuggestions="false"
|
||||||
inputMode={inputMode}
|
inputMode={inputMode}
|
||||||
onChange={(e) => handleChange(e.target.value)}
|
onChange={(e) => handleChange(e.target.value)}
|
||||||
onPaste={(e) => onPaste?.(e.clipboardData.getData("Text"))}
|
onPaste={(e) => onPaste?.(e.clipboardData.getData("Text"))}
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import { useStateWithDeps } from "../../hooks/useStateWithDeps";
|
|||||||
import { generateId } from "../../lib/generateId";
|
import { generateId } from "../../lib/generateId";
|
||||||
import { Button } from "./Button";
|
import { Button } from "./Button";
|
||||||
import { IconButton, type IconButtonProps } from "./IconButton";
|
import { IconButton, type IconButtonProps } from "./IconButton";
|
||||||
|
import { IconTooltip } from "./IconTooltip";
|
||||||
import { Label } from "./Label";
|
import { Label } from "./Label";
|
||||||
|
|
||||||
interface Props<T extends string> {
|
interface Props<T extends string> {
|
||||||
@@ -36,11 +37,15 @@ export function SegmentedControl<T extends string>({
|
|||||||
const containerRef = useRef<HTMLDivElement>(null);
|
const containerRef = useRef<HTMLDivElement>(null);
|
||||||
const id = useRef(`input-${generateId()}`);
|
const id = useRef(`input-${generateId()}`);
|
||||||
|
|
||||||
|
// A visually hidden label has nowhere to show the help, so the last option carries it
|
||||||
|
const inlineHelp =
|
||||||
|
hideLabel && help ? <IconTooltip tabIndex={-1} content={help} iconSize="xs" /> : null;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="w-full grid">
|
<div className="w-full grid">
|
||||||
<Label
|
<Label
|
||||||
htmlFor={id.current}
|
htmlFor={id.current}
|
||||||
help={help}
|
help={hideLabel ? undefined : help}
|
||||||
visuallyHidden={hideLabel}
|
visuallyHidden={hideLabel}
|
||||||
className={classNames(labelClassName)}
|
className={classNames(labelClassName)}
|
||||||
>
|
>
|
||||||
@@ -78,9 +83,10 @@ export function SegmentedControl<T extends string>({
|
|||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{options.map((o) => {
|
{options.map((o, i) => {
|
||||||
const isSelected = selectedValue === o.value;
|
const isSelected = selectedValue === o.value;
|
||||||
const isActive = value === o.value;
|
const isActive = value === o.value;
|
||||||
|
const rightSlot = i === options.length - 1 ? inlineHelp : null;
|
||||||
if (o.icon == null) {
|
if (o.icon == null) {
|
||||||
return (
|
return (
|
||||||
<Button
|
<Button
|
||||||
@@ -95,6 +101,7 @@ export function SegmentedControl<T extends string>({
|
|||||||
isActive && "text-text!",
|
isActive && "text-text!",
|
||||||
"focus:ring-1 focus:ring-border-focus",
|
"focus:ring-1 focus:ring-border-focus",
|
||||||
)}
|
)}
|
||||||
|
rightSlot={rightSlot}
|
||||||
onClick={() => onChange(o.value)}
|
onClick={() => onChange(o.value)}
|
||||||
>
|
>
|
||||||
{o.label}
|
{o.label}
|
||||||
@@ -117,6 +124,7 @@ export function SegmentedControl<T extends string>({
|
|||||||
)}
|
)}
|
||||||
title={o.label}
|
title={o.label}
|
||||||
icon={o.icon}
|
icon={o.icon}
|
||||||
|
rightSlot={rightSlot}
|
||||||
onClick={() => onChange(o.value)}
|
onClick={() => onChange(o.value)}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import type { AnyModel } from "@yaakapp-internal/models";
|
|||||||
import { patchModel } from "@yaakapp-internal/models";
|
import { patchModel } from "@yaakapp-internal/models";
|
||||||
import classNames from "classnames";
|
import classNames from "classnames";
|
||||||
import type { ReactNode } from "react";
|
import type { ReactNode } from "react";
|
||||||
|
import { createContext, useContext, useEffect, useRef, useState } from "react";
|
||||||
import { CopyIconButton } from "../CopyIconButton";
|
import { CopyIconButton } from "../CopyIconButton";
|
||||||
import { Checkbox } from "./Checkbox";
|
import { Checkbox } from "./Checkbox";
|
||||||
import { IconButton, type IconButtonProps } from "./IconButton";
|
import { IconButton, type IconButtonProps } from "./IconButton";
|
||||||
@@ -19,11 +20,31 @@ type SettingRowBaseProps = {
|
|||||||
controlClassName?: string;
|
controlClassName?: string;
|
||||||
description?: ReactNode;
|
description?: ReactNode;
|
||||||
disabled?: boolean;
|
disabled?: boolean;
|
||||||
|
/** Matched against the surrounding `SettingsList` highlight to point this row out when it opens */
|
||||||
|
highlightKey?: string;
|
||||||
title: ReactNode;
|
title: ReactNode;
|
||||||
};
|
};
|
||||||
|
|
||||||
export function SettingsList({ children, className }: { children: ReactNode; className?: string }) {
|
const SettingsHighlightContext = createContext<string | null>(null);
|
||||||
return <div className={classNames("w-full", className)}>{children}</div>;
|
|
||||||
|
const FOCUSABLE =
|
||||||
|
"button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex='-1'])";
|
||||||
|
|
||||||
|
export function SettingsList({
|
||||||
|
children,
|
||||||
|
className,
|
||||||
|
highlight = null,
|
||||||
|
}: {
|
||||||
|
children: ReactNode;
|
||||||
|
className?: string;
|
||||||
|
/** The `highlightKey` of a row to scroll to, focus, and briefly highlight */
|
||||||
|
highlight?: string | null;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<SettingsHighlightContext.Provider value={highlight}>
|
||||||
|
<div className={classNames("w-full", className)}>{children}</div>
|
||||||
|
</SettingsHighlightContext.Provider>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function SettingsSection({
|
export function SettingsSection({
|
||||||
@@ -58,17 +79,37 @@ export function SettingRow({
|
|||||||
controlClassName,
|
controlClassName,
|
||||||
description,
|
description,
|
||||||
disabled,
|
disabled,
|
||||||
|
highlightKey,
|
||||||
title,
|
title,
|
||||||
}: {
|
}: {
|
||||||
children: ReactNode;
|
children: ReactNode;
|
||||||
} & SettingRowBaseProps) {
|
} & SettingRowBaseProps) {
|
||||||
|
const highlight = useContext(SettingsHighlightContext);
|
||||||
|
const isHighlighted = highlightKey != null && highlightKey === highlight;
|
||||||
|
const [flashing, setFlashing] = useState(isHighlighted);
|
||||||
|
const rowRef = useRef<HTMLDivElement>(null);
|
||||||
|
const controlRef = useRef<HTMLDivElement>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!isHighlighted) return;
|
||||||
|
rowRef.current?.scrollIntoView({ block: "nearest" });
|
||||||
|
controlRef.current?.querySelector<HTMLElement>(FOCUSABLE)?.focus();
|
||||||
|
}, [isHighlighted]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
|
ref={rowRef}
|
||||||
aria-disabled={disabled || undefined}
|
aria-disabled={disabled || undefined}
|
||||||
|
onAnimationEnd={(event) => {
|
||||||
|
if (event.target === event.currentTarget) setFlashing(false);
|
||||||
|
}}
|
||||||
className={classNames(
|
className={classNames(
|
||||||
className,
|
className,
|
||||||
"@container border-b border-border-subtle py-4",
|
"@container border-b border-border-subtle py-4",
|
||||||
disabled && "opacity-disabled",
|
disabled && "opacity-disabled",
|
||||||
|
// Drawn on a layer so the tint gets even padding and stops short of the row's border
|
||||||
|
flashing &&
|
||||||
|
"relative isolate before:absolute before:-inset-x-3 before:inset-y-1 before:-z-10 before:rounded-lg before:animate-settingHighlight",
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
<div
|
<div
|
||||||
@@ -84,6 +125,7 @@ export function SettingRow({
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<div
|
<div
|
||||||
|
ref={controlRef}
|
||||||
className={classNames(
|
className={classNames(
|
||||||
"flex min-w-0 items-center justify-start @[40rem]:justify-end",
|
"flex min-w-0 items-center justify-start @[40rem]:justify-end",
|
||||||
controlClassName,
|
controlClassName,
|
||||||
|
|||||||
@@ -1,10 +1,8 @@
|
|||||||
import { useGitBranchInfo, useGitMutations } from "@yaakapp-internal/git";
|
import { useGitBranchInfo, useGitMutations } from "@yaakapp-internal/git";
|
||||||
import type { WorkspaceMeta } from "@yaakapp-internal/models";
|
|
||||||
import classNames from "classnames";
|
import classNames from "classnames";
|
||||||
import { useAtomValue } from "jotai";
|
import { useAtomValue } from "jotai";
|
||||||
import type { HTMLAttributes } from "react";
|
import type { HTMLAttributes } from "react";
|
||||||
import { forwardRef, useCallback, useMemo } from "react";
|
import { forwardRef, useCallback, useMemo } from "react";
|
||||||
import { openWorkspaceSettings } from "../../commands/openWorkspaceSettings";
|
|
||||||
import { activeWorkspaceAtom, activeWorkspaceMetaAtom } from "../../hooks/useActiveWorkspace";
|
import { activeWorkspaceAtom, activeWorkspaceMetaAtom } from "../../hooks/useActiveWorkspace";
|
||||||
import { useKeyValue } from "../../hooks/useKeyValue";
|
import { useKeyValue } from "../../hooks/useKeyValue";
|
||||||
import { useRandomKey } from "../../hooks/useRandomKey";
|
import { useRandomKey } from "../../hooks/useRandomKey";
|
||||||
@@ -18,6 +16,7 @@ import { showErrorToast, showToast } from "../../lib/toast";
|
|||||||
import type { DropdownItem } from "../core/Dropdown";
|
import type { DropdownItem } from "../core/Dropdown";
|
||||||
import { Dropdown } from "../core/Dropdown";
|
import { Dropdown } from "../core/Dropdown";
|
||||||
import { Banner, Icon, InlineCode } from "@yaakapp-internal/ui";
|
import { Banner, Icon, InlineCode } from "@yaakapp-internal/ui";
|
||||||
|
import { SyncWorkspaceHint } from "../hints/SyncWorkspaceHint";
|
||||||
import { useGitCallbacks } from "./callbacks";
|
import { useGitCallbacks } from "./callbacks";
|
||||||
import { GitCommitDialog } from "./GitCommitDialog";
|
import { GitCommitDialog } from "./GitCommitDialog";
|
||||||
import { GitRemotesDialog } from "./GitRemotesDialog";
|
import { GitRemotesDialog } from "./GitRemotesDialog";
|
||||||
@@ -31,7 +30,7 @@ export function GitDropdown() {
|
|||||||
if (workspaceMeta == null) return null;
|
if (workspaceMeta == null) return null;
|
||||||
|
|
||||||
if (workspaceMeta.settingSyncDir == null) {
|
if (workspaceMeta.settingSyncDir == null) {
|
||||||
return <SetupSyncDropdown workspaceMeta={workspaceMeta} />;
|
return <SyncWorkspaceHint workspaceId={workspaceMeta.workspaceId} />;
|
||||||
}
|
}
|
||||||
|
|
||||||
return <SyncDropdownWithSyncDir syncDir={workspaceMeta.settingSyncDir} />;
|
return <SyncDropdownWithSyncDir syncDir={workspaceMeta.settingSyncDir} />;
|
||||||
@@ -567,64 +566,6 @@ const GitMenuButton = forwardRef<HTMLButtonElement, HTMLAttributes<HTMLButtonEle
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
function SetupSyncDropdown({ workspaceMeta }: { workspaceMeta: WorkspaceMeta }) {
|
|
||||||
const { value: hidden, set: setHidden } = useKeyValue<Record<string, boolean>>({
|
|
||||||
key: "setup_sync",
|
|
||||||
fallback: {},
|
|
||||||
});
|
|
||||||
|
|
||||||
if (hidden == null || hidden[workspaceMeta.workspaceId]) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
const banner = (
|
|
||||||
<Banner color="info">
|
|
||||||
When enabled, workspace data syncs to the chosen folder as text files, ideal for backup and
|
|
||||||
Git collaboration.
|
|
||||||
</Banner>
|
|
||||||
);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Dropdown
|
|
||||||
fullWidth
|
|
||||||
items={[
|
|
||||||
{
|
|
||||||
type: "content",
|
|
||||||
label: banner,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
color: "success",
|
|
||||||
label: "Open Workspace Settings",
|
|
||||||
leftSlot: <Icon icon="settings" />,
|
|
||||||
onSelect: () => openWorkspaceSettings("settings"),
|
|
||||||
},
|
|
||||||
{ type: "separator" },
|
|
||||||
{
|
|
||||||
label: "Hide This Message",
|
|
||||||
leftSlot: <Icon icon="eye_closed" />,
|
|
||||||
async onSelect() {
|
|
||||||
const confirmed = await showConfirm({
|
|
||||||
id: "hide-sync-menu-prompt",
|
|
||||||
title: "Hide Setup Message",
|
|
||||||
description: "You can configure filesystem sync or Git it in the workspace settings",
|
|
||||||
});
|
|
||||||
if (confirmed) {
|
|
||||||
await setHidden((prev) => ({ ...prev, [workspaceMeta.workspaceId]: true }));
|
|
||||||
}
|
|
||||||
},
|
|
||||||
},
|
|
||||||
]}
|
|
||||||
>
|
|
||||||
<GitMenuButton>
|
|
||||||
<div className="text-sm text-text-subtle grid grid-cols-[auto_minmax(0,1fr)] items-center gap-2">
|
|
||||||
<Icon icon="wrench" />
|
|
||||||
<div className="truncate">Setup FS Sync or Git</div>
|
|
||||||
</div>
|
|
||||||
</GitMenuButton>
|
|
||||||
</Dropdown>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function SetupGitDropdown({
|
function SetupGitDropdown({
|
||||||
workspaceId,
|
workspaceId,
|
||||||
initRepo,
|
initRepo,
|
||||||
|
|||||||
@@ -0,0 +1,29 @@
|
|||||||
|
import type { HttpResponse } from "@yaakapp-internal/models";
|
||||||
|
import { httpRequestsAtom } from "@yaakapp-internal/models";
|
||||||
|
import { InlineCode } from "@yaakapp-internal/ui";
|
||||||
|
import { useAtomValue } from "jotai";
|
||||||
|
import { FeatureHint } from "../core/FeatureHint";
|
||||||
|
|
||||||
|
const MIN_REQUESTS = 2;
|
||||||
|
const DOCS_URL = "https://yaak.app/docs/templating/request-chaining-scripting";
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
response: HttpResponse;
|
||||||
|
mimeType: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A successful JSON response, in a workspace with somewhere to send its values. */
|
||||||
|
export function ChainingHint({ response, mimeType }: Props) {
|
||||||
|
const requestCount = useAtomValue(httpRequestsAtom).length;
|
||||||
|
const status = response.status ?? 0;
|
||||||
|
const isJson = mimeType != null && /json/i.test(mimeType);
|
||||||
|
if (response.state !== "closed" || status < 200 || status >= 300) return null;
|
||||||
|
if (!isJson || requestCount < MIN_REQUESTS) return null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<FeatureHint id="chaining" className="mx-3 mt-1 shrink-0" docsUrl={DOCS_URL}>
|
||||||
|
Need a value from here in another request? Press <InlineCode>Ctrl+Space</InlineCode> in any
|
||||||
|
field and pick <InlineCode>response()</InlineCode> to pull it out with a JSONPath
|
||||||
|
</FeatureHint>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
import { useEnvironmentsBreakdown } from "../../hooks/useEnvironmentsBreakdown";
|
||||||
|
import {
|
||||||
|
addVariableToBaseEnvironment,
|
||||||
|
isTemplate,
|
||||||
|
variableTemplate,
|
||||||
|
} from "../../lib/addVariableToBaseEnvironment";
|
||||||
|
import { dismissFeatureHint, FeatureHint } from "../core/FeatureHint";
|
||||||
|
|
||||||
|
const HINT_ID = "secret-variable";
|
||||||
|
const DOCS_URL = "https://yaak.app/docs/templating/environments-and-variables";
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
/** Becomes the variable name, so it should describe the value (eg. "password", "token") */
|
||||||
|
name: string;
|
||||||
|
value: string;
|
||||||
|
onReplace: (template: string) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A literal secret typed straight into an auth field. Offer to move it to a variable so the
|
||||||
|
* request references it instead of holding it.
|
||||||
|
*/
|
||||||
|
export function SecretVariableHint({ name, value, onReplace }: Props) {
|
||||||
|
const { baseEnvironment } = useEnvironmentsBreakdown();
|
||||||
|
if (value.trim() === "" || isTemplate(value) || baseEnvironment == null) return null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<FeatureHint
|
||||||
|
id={HINT_ID}
|
||||||
|
docsUrl={DOCS_URL}
|
||||||
|
action={{
|
||||||
|
label: "Move to Variable",
|
||||||
|
onClick: async () => {
|
||||||
|
const finalName = await addVariableToBaseEnvironment(baseEnvironment, name, value);
|
||||||
|
onReplace(variableTemplate(finalName));
|
||||||
|
await dismissFeatureHint(HINT_ID);
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Typing this in by hand? Store it in a variable to reuse it across requests and swap it per
|
||||||
|
environment.
|
||||||
|
</FeatureHint>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
import { httpRequestsAtom, patchModel } from "@yaakapp-internal/models";
|
||||||
|
import { InlineCode } from "@yaakapp-internal/ui";
|
||||||
|
import { useAtomValue } from "jotai";
|
||||||
|
import { useMemo } from "react";
|
||||||
|
import { useEnvironmentsBreakdown } from "../../hooks/useEnvironmentsBreakdown";
|
||||||
|
import {
|
||||||
|
addVariableToBaseEnvironment,
|
||||||
|
isTemplate,
|
||||||
|
variableTemplate,
|
||||||
|
} from "../../lib/addVariableToBaseEnvironment";
|
||||||
|
import { FeatureHint } from "../core/FeatureHint";
|
||||||
|
|
||||||
|
const MIN_SHARED_REQUESTS = 3;
|
||||||
|
const DOCS_URL = "https://yaak.app/docs/templating/environments-and-variables";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Once a few requests spell out the same literal origin, offer to hoist it into a variable and
|
||||||
|
* rewrite them all at once.
|
||||||
|
*/
|
||||||
|
export function SharedOriginHint() {
|
||||||
|
const requests = useAtomValue(httpRequestsAtom);
|
||||||
|
const { baseEnvironment } = useEnvironmentsBreakdown();
|
||||||
|
|
||||||
|
const shared = useMemo(() => {
|
||||||
|
const byOrigin = new Map<string, typeof requests>();
|
||||||
|
for (const r of requests) {
|
||||||
|
if (isTemplate(r.url)) continue;
|
||||||
|
const origin = literalOrigin(r.url);
|
||||||
|
if (origin == null) continue;
|
||||||
|
byOrigin.set(origin, [...(byOrigin.get(origin) ?? []), r]);
|
||||||
|
}
|
||||||
|
let best: { origin: string; requests: typeof requests } | null = null;
|
||||||
|
for (const [origin, group] of byOrigin) {
|
||||||
|
if (group.length >= MIN_SHARED_REQUESTS && group.length > (best?.requests.length ?? 0)) {
|
||||||
|
best = { origin, requests: group };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return best;
|
||||||
|
}, [requests]);
|
||||||
|
|
||||||
|
if (shared == null || baseEnvironment == null) return null;
|
||||||
|
|
||||||
|
const { origin } = shared;
|
||||||
|
const count = shared.requests.length;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<FeatureHint
|
||||||
|
id={`shared-origin:${origin}`}
|
||||||
|
className="mt-1"
|
||||||
|
docsUrl={DOCS_URL}
|
||||||
|
action={{
|
||||||
|
label: "Use a Variable",
|
||||||
|
onClick: async () => {
|
||||||
|
const name = await addVariableToBaseEnvironment(baseEnvironment, "base_url", origin);
|
||||||
|
const template = variableTemplate(name);
|
||||||
|
await Promise.all(
|
||||||
|
shared.requests.map((r) =>
|
||||||
|
patchModel(r, { url: template + r.url.slice(origin.length) }),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{count} requests start with <InlineCode>{origin}</InlineCode>. Put it in a variable and switch
|
||||||
|
hosts by switching environments.
|
||||||
|
</FeatureHint>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function literalOrigin(url: string): string | null {
|
||||||
|
const m = /^(https?:\/\/[^/?#\s]+)/i.exec(url.trim());
|
||||||
|
return m?.[1] ?? null;
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
import { VStack } from "@yaakapp-internal/ui";
|
||||||
|
import { openWorkspaceSettings } from "../../commands/openWorkspaceSettings";
|
||||||
|
import { useKeyValue } from "../../hooks/useKeyValue";
|
||||||
|
import { showToast } from "../../lib/toast";
|
||||||
|
import { FeatureHint } from "../core/FeatureHint";
|
||||||
|
|
||||||
|
const DOCS_URL = "https://yaak.app/docs/collaboration/local-directory-git-sync";
|
||||||
|
|
||||||
|
/** What the sidebar's Git slot shows while the workspace only lives in the app's database. */
|
||||||
|
export function SyncWorkspaceHint({ workspaceId }: { workspaceId: string }) {
|
||||||
|
// Hidden from the menu this replaced, so honor it
|
||||||
|
const { value: legacyHidden } = useKeyValue<Record<string, boolean>>({
|
||||||
|
key: "setup_sync",
|
||||||
|
fallback: {},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (legacyHidden == null || legacyHidden[workspaceId]) return null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<FeatureHint
|
||||||
|
id={`sync-workspace:${workspaceId}`}
|
||||||
|
className="mx-2 mb-2!"
|
||||||
|
docsUrl={DOCS_URL}
|
||||||
|
action={{ label: "Configure", onClick: () => openWorkspaceSettings("settings", "sync_dir") }}
|
||||||
|
onDismiss={showSyncLocationToast}
|
||||||
|
>
|
||||||
|
Sync this workspace to a folder of plain files to back it up or track it with Git.
|
||||||
|
</FeatureHint>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function showSyncLocationToast() {
|
||||||
|
showToast({
|
||||||
|
id: "sync-hint-dismissed",
|
||||||
|
color: "info",
|
||||||
|
timeout: 8000,
|
||||||
|
message: (
|
||||||
|
<VStack>
|
||||||
|
<h2 className="font-semibold">Sync whenever you're ready</h2>
|
||||||
|
<p className="text-text-subtle text-sm">Directory sync and Git are in Workspace Settings</p>
|
||||||
|
</VStack>
|
||||||
|
),
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
import type { Environment } from "@yaakapp-internal/models";
|
||||||
|
import { patchModel } from "@yaakapp-internal/models";
|
||||||
|
import { generateId } from "./generateId";
|
||||||
|
|
||||||
|
/** Adds a variable, suffixing the name if it's taken, and returns the name that was used. */
|
||||||
|
export async function addVariableToBaseEnvironment(
|
||||||
|
environment: Environment,
|
||||||
|
name: string,
|
||||||
|
value: string,
|
||||||
|
): Promise<string> {
|
||||||
|
const taken = new Set(environment.variables.map((v) => v.name));
|
||||||
|
let finalName = name;
|
||||||
|
for (let i = 2; taken.has(finalName); i++) {
|
||||||
|
finalName = `${name}_${i}`;
|
||||||
|
}
|
||||||
|
await patchModel(environment, {
|
||||||
|
variables: [
|
||||||
|
...environment.variables,
|
||||||
|
{ id: generateId(), name: finalName, value, enabled: true },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
return finalName;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function variableTemplate(name: string) {
|
||||||
|
return `\${[ ${name} ]}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isTemplate(value: string) {
|
||||||
|
return value.includes("${[");
|
||||||
|
}
|
||||||
@@ -99,6 +99,6 @@
|
|||||||
"vite-plugin-static-copy": "^3.3.0",
|
"vite-plugin-static-copy": "^3.3.0",
|
||||||
"vite-plugin-svgr": "^4.5.0",
|
"vite-plugin-svgr": "^4.5.0",
|
||||||
"vite-plugin-wasm": "^3.5.0",
|
"vite-plugin-wasm": "^3.5.0",
|
||||||
"vite-plus": "^0.2.9"
|
"vite-plus": "^0.3.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Vendored
+8
@@ -0,0 +1,8 @@
|
|||||||
|
import "react";
|
||||||
|
|
||||||
|
declare module "react" {
|
||||||
|
interface HTMLAttributes<T> {
|
||||||
|
// Not in @types/react yet; opts editable elements out of macOS Writing Tools
|
||||||
|
writingsuggestions?: "true" | "false";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -32,6 +32,6 @@
|
|||||||
"babel-plugin-react-compiler": "^1.0.0",
|
"babel-plugin-react-compiler": "^1.0.0",
|
||||||
"typescript": "^5.8.3",
|
"typescript": "^5.8.3",
|
||||||
"vite": "npm:@voidzero-dev/vite-plus-core@^0.2.9",
|
"vite": "npm:@voidzero-dev/vite-plus-core@^0.2.9",
|
||||||
"vite-plus": "^0.2.9"
|
"vite-plus": "^0.3.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -39,7 +39,7 @@ tokio = { workspace = true, features = [
|
|||||||
] }
|
] }
|
||||||
walkdir = "2"
|
walkdir = "2"
|
||||||
webbrowser = "1"
|
webbrowser = "1"
|
||||||
zip = "4"
|
zip = "7"
|
||||||
yaak = { workspace = true }
|
yaak = { workspace = true }
|
||||||
yaak-api = { workspace = true }
|
yaak-api = { workspace = true }
|
||||||
yaak-core = { workspace = true }
|
yaak-core = { workspace = true }
|
||||||
|
|||||||
@@ -1,19 +1,12 @@
|
|||||||
---
|
---
|
||||||
name: use-yaak
|
name: use-yaak
|
||||||
description: >
|
description: >
|
||||||
Build and run HTTP API requests with the Yaak CLI (`yaak`): create workspaces,
|
Use when the user mentions Yaak, a Yaak workspace, or the `yaak` command, or
|
||||||
folders, environments and variables, author HTTP requests, configure
|
asks to call, hit, or smoke test HTTP/REST endpoints, save or organize API
|
||||||
authentication (OAuth 2.0, bearer tokens, API keys, basic, JWT, AWS SigV4),
|
requests for reuse or manual testing, configure auth on saved requests, import
|
||||||
send them individually or a whole folder/workspace at once, chain one
|
an OpenAPI spec, a Postman or Insomnia collection, or a cURL command, or run
|
||||||
request's response into the next, and import existing APIs from OpenAPI,
|
saved requests across environments. Prefer over one-off `curl` when requests
|
||||||
Postman, Insomnia, or cURL. Use this skill whenever the user mentions Yaak, a
|
should be saved, reused, shared, or run as a set.
|
||||||
Yaak workspace, or the `yaak` command, and also when they ask to try, hit,
|
|
||||||
call, exercise, or smoke test an HTTP or REST endpoint, to save or organize
|
|
||||||
API requests for reuse, to set up API requests for manual testing, to add auth
|
|
||||||
to a saved request, to turn an OpenAPI or Postman collection into runnable
|
|
||||||
requests, or to run a saved request suite against staging versus production.
|
|
||||||
Prefer this over one-off `curl` commands whenever the requests should be
|
|
||||||
saved, reused, shared, or run as a set.
|
|
||||||
allowed-tools: Bash(yaak:*), Bash(which:*), Bash(command:*), Bash(npm:*), Bash(npx:*)
|
allowed-tools: Bash(yaak:*), Bash(which:*), Bash(command:*), Bash(npm:*), Bash(npx:*)
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -34,7 +27,7 @@ only for publishing plugins to the Yaak registry.
|
|||||||
Two consequences worth holding onto. Requests you create are permanent user data
|
Two consequences worth holding onto. Requests you create are permanent user data
|
||||||
in an app they use, not scratch files, so name them the way the user would and
|
in an app they use, not scratch files, so name them the way the user would and
|
||||||
clean up anything created just to test. And because the app is right there, the
|
clean up anything created just to test. And because the app is right there, the
|
||||||
CLI is usually the wrong place to *read* a response in detail; it is the right
|
CLI is usually the wrong place to _read_ a response in detail; it is the right
|
||||||
place to build, organize, and run requests.
|
place to build, organize, and run requests.
|
||||||
|
|
||||||
## The CLI describes itself
|
## The CLI describes itself
|
||||||
|
|||||||
@@ -49,8 +49,11 @@ fn schema(pretty: bool) -> CommandResult {
|
|||||||
fn list(ctx: &CliContext, workspace_id: Option<&str>) -> CommandResult {
|
fn list(ctx: &CliContext, workspace_id: Option<&str>) -> CommandResult {
|
||||||
let workspace_id = resolve_workspace_id(ctx, workspace_id, "environment list")?;
|
let workspace_id = resolve_workspace_id(ctx, workspace_id, "environment list")?;
|
||||||
let environments = ctx
|
let environments = ctx
|
||||||
.db()
|
.query_manager()
|
||||||
.list_environments_ensure_base(&workspace_id)
|
.with_tx(|tx| {
|
||||||
|
tx.ensure_base_environment(&workspace_id)?;
|
||||||
|
tx.list_environments(&workspace_id)
|
||||||
|
})
|
||||||
.map_err(|e| format!("Failed to list environments: {e}"))?;
|
.map_err(|e| format!("Failed to list environments: {e}"))?;
|
||||||
|
|
||||||
if environments.is_empty() {
|
if environments.is_empty() {
|
||||||
@@ -111,8 +114,8 @@ fn create(
|
|||||||
}
|
}
|
||||||
|
|
||||||
let created = ctx
|
let created = ctx
|
||||||
.db()
|
.query_manager()
|
||||||
.upsert_environment(&environment, &UpdateSource::Sync)
|
.with_tx(|tx| tx.upsert_environment(&environment, &UpdateSource::Sync))
|
||||||
.map_err(|e| format!("Failed to create environment: {e}"))?;
|
.map_err(|e| format!("Failed to create environment: {e}"))?;
|
||||||
|
|
||||||
println!("Created environment: {}", created.id);
|
println!("Created environment: {}", created.id);
|
||||||
@@ -133,8 +136,8 @@ fn create(
|
|||||||
};
|
};
|
||||||
|
|
||||||
let created = ctx
|
let created = ctx
|
||||||
.db()
|
.query_manager()
|
||||||
.upsert_environment(&environment, &UpdateSource::Sync)
|
.with_tx(|tx| tx.upsert_environment(&environment, &UpdateSource::Sync))
|
||||||
.map_err(|e| format!("Failed to create environment: {e}"))?;
|
.map_err(|e| format!("Failed to create environment: {e}"))?;
|
||||||
|
|
||||||
println!("Created environment: {}", created.id);
|
println!("Created environment: {}", created.id);
|
||||||
@@ -152,8 +155,8 @@ fn update(ctx: &CliContext, json: Option<String>, json_input: Option<String>) ->
|
|||||||
let updated = apply_merge_patch(&existing, &patch, &id, "environment update")?;
|
let updated = apply_merge_patch(&existing, &patch, &id, "environment update")?;
|
||||||
|
|
||||||
let saved = ctx
|
let saved = ctx
|
||||||
.db()
|
.query_manager()
|
||||||
.upsert_environment(&updated, &UpdateSource::Sync)
|
.with_tx(|tx| tx.upsert_environment(&updated, &UpdateSource::Sync))
|
||||||
.map_err(|e| format!("Failed to update environment: {e}"))?;
|
.map_err(|e| format!("Failed to update environment: {e}"))?;
|
||||||
|
|
||||||
println!("Updated environment: {}", saved.id);
|
println!("Updated environment: {}", saved.id);
|
||||||
@@ -167,8 +170,8 @@ fn delete(ctx: &CliContext, environment_id: &str, yes: bool) -> CommandResult {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let deleted = ctx
|
let deleted = ctx
|
||||||
.db()
|
.query_manager()
|
||||||
.delete_environment_by_id(environment_id, &UpdateSource::Sync)
|
.with_tx(|tx| tx.delete_environment_by_id(environment_id, &UpdateSource::Sync))
|
||||||
.map_err(|e| format!("Failed to delete environment: {e}"))?;
|
.map_err(|e| format!("Failed to delete environment: {e}"))?;
|
||||||
|
|
||||||
println!("Deleted environment: {}", deleted.id);
|
println!("Deleted environment: {}", deleted.id);
|
||||||
|
|||||||
@@ -102,8 +102,8 @@ fn create(
|
|||||||
)?;
|
)?;
|
||||||
|
|
||||||
let created = ctx
|
let created = ctx
|
||||||
.db()
|
.query_manager()
|
||||||
.upsert_folder(&folder, &UpdateSource::Sync)
|
.with_tx(|tx| tx.upsert_folder(&folder, &UpdateSource::Sync))
|
||||||
.map_err(|e| format!("Failed to create folder: {e}"))?;
|
.map_err(|e| format!("Failed to create folder: {e}"))?;
|
||||||
|
|
||||||
println!("Created folder: {}", created.id);
|
println!("Created folder: {}", created.id);
|
||||||
@@ -118,8 +118,8 @@ fn create(
|
|||||||
let folder = Folder { workspace_id, name, ..Default::default() };
|
let folder = Folder { workspace_id, name, ..Default::default() };
|
||||||
|
|
||||||
let created = ctx
|
let created = ctx
|
||||||
.db()
|
.query_manager()
|
||||||
.upsert_folder(&folder, &UpdateSource::Sync)
|
.with_tx(|tx| tx.upsert_folder(&folder, &UpdateSource::Sync))
|
||||||
.map_err(|e| format!("Failed to create folder: {e}"))?;
|
.map_err(|e| format!("Failed to create folder: {e}"))?;
|
||||||
|
|
||||||
println!("Created folder: {}", created.id);
|
println!("Created folder: {}", created.id);
|
||||||
@@ -135,8 +135,8 @@ fn update(ctx: &CliContext, json: Option<String>, json_input: Option<String>) ->
|
|||||||
let updated = apply_merge_patch(&existing, &patch, &id, "folder update")?;
|
let updated = apply_merge_patch(&existing, &patch, &id, "folder update")?;
|
||||||
|
|
||||||
let saved = ctx
|
let saved = ctx
|
||||||
.db()
|
.query_manager()
|
||||||
.upsert_folder(&updated, &UpdateSource::Sync)
|
.with_tx(|tx| tx.upsert_folder(&updated, &UpdateSource::Sync))
|
||||||
.map_err(|e| format!("Failed to update folder: {e}"))?;
|
.map_err(|e| format!("Failed to update folder: {e}"))?;
|
||||||
|
|
||||||
println!("Updated folder: {}", saved.id);
|
println!("Updated folder: {}", saved.id);
|
||||||
@@ -150,8 +150,8 @@ fn delete(ctx: &CliContext, folder_id: &str, yes: bool) -> CommandResult {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let deleted = ctx
|
let deleted = ctx
|
||||||
.db()
|
.query_manager()
|
||||||
.delete_folder_by_id(folder_id, &UpdateSource::Sync)
|
.with_tx(|tx| tx.delete_folder_by_id(folder_id, &UpdateSource::Sync))
|
||||||
.map_err(|e| format!("Failed to delete folder: {e}"))?;
|
.map_err(|e| format!("Failed to delete folder: {e}"))?;
|
||||||
|
|
||||||
println!("Deleted folder: {}", deleted.id);
|
println!("Deleted folder: {}", deleted.id);
|
||||||
|
|||||||
@@ -68,7 +68,9 @@ async fn import(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
let destination = match workspace_id {
|
let destination = match workspace_id {
|
||||||
Some(workspace_id) => ImportDestination::ExistingWorkspace { workspace_id, folder_id: None },
|
Some(workspace_id) => {
|
||||||
|
ImportDestination::ExistingWorkspace { workspace_id, folder_id: None }
|
||||||
|
}
|
||||||
None => ImportDestination::NewWorkspace,
|
None => ImportDestination::NewWorkspace,
|
||||||
};
|
};
|
||||||
let plan = import::plan_import_resources(
|
let plan = import::plan_import_resources(
|
||||||
@@ -113,6 +115,10 @@ fn format_skipped(items: &[ImportPlanItem]) -> Option<String> {
|
|||||||
if keep_local > 0 {
|
if keep_local > 0 {
|
||||||
parts.push(format!("{keep_local} with local edits"));
|
parts.push(format!("{keep_local} with local edits"));
|
||||||
}
|
}
|
||||||
|
let ignored = count(ImportPlanAction::Ignored);
|
||||||
|
if ignored > 0 {
|
||||||
|
parts.push(format!("{ignored} ignored"));
|
||||||
|
}
|
||||||
let unchanged = count(ImportPlanAction::Unchanged);
|
let unchanged = count(ImportPlanAction::Unchanged);
|
||||||
if unchanged > 0 {
|
if unchanged > 0 {
|
||||||
parts.push(format!("{unchanged} unchanged"));
|
parts.push(format!("{unchanged} unchanged"));
|
||||||
|
|||||||
@@ -348,17 +348,19 @@ async fn install_from_directory(context: &CliContext, source: &str) -> CommandRe
|
|||||||
ui::info(&format!("Installing plugin from directory {}", plugin_dir.display()));
|
ui::info(&format!("Installing plugin from directory {}", plugin_dir.display()));
|
||||||
|
|
||||||
let plugin = context
|
let plugin = context
|
||||||
.db()
|
.query_manager()
|
||||||
.upsert_plugin(
|
.with_tx(|tx| {
|
||||||
&Plugin {
|
tx.upsert_plugin(
|
||||||
directory: plugin_dir_str,
|
&Plugin {
|
||||||
url: None,
|
directory: plugin_dir_str,
|
||||||
enabled: true,
|
url: None,
|
||||||
source: PluginSource::Filesystem,
|
enabled: true,
|
||||||
..Default::default()
|
source: PluginSource::Filesystem,
|
||||||
},
|
..Default::default()
|
||||||
&UpdateSource::Background,
|
},
|
||||||
)
|
&UpdateSource::Background,
|
||||||
|
)
|
||||||
|
})
|
||||||
.map_err(|err| format!("Failed to save plugin in database: {err}"))?;
|
.map_err(|err| format!("Failed to save plugin in database: {err}"))?;
|
||||||
|
|
||||||
let plugin_context = PluginContext::new(Some("cli".to_string()), None);
|
let plugin_context = PluginContext::new(Some("cli".to_string()), None);
|
||||||
@@ -883,11 +885,8 @@ mod tests {
|
|||||||
fs::create_dir_all(root.join("build")).expect("create build");
|
fs::create_dir_all(root.join("build")).expect("create build");
|
||||||
fs::create_dir_all(root.join("vendor")).expect("create vendor");
|
fs::create_dir_all(root.join("vendor")).expect("create vendor");
|
||||||
fs::write(root.join("vendor/core_bg.wasm"), "asset").expect("write asset");
|
fs::write(root.join("vendor/core_bg.wasm"), "asset").expect("write asset");
|
||||||
fs::write(
|
fs::write(root.join("package.json"), r#"{"yaak":{"buildAssets":["vendor/core_bg.wasm"]}}"#)
|
||||||
root.join("package.json"),
|
.expect("write package.json");
|
||||||
r#"{"yaak":{"buildAssets":["vendor/core_bg.wasm"]}}"#,
|
|
||||||
)
|
|
||||||
.expect("write package.json");
|
|
||||||
|
|
||||||
copy_build_assets(root).expect("copy assets");
|
copy_build_assets(root).expect("copy assets");
|
||||||
|
|
||||||
|
|||||||
@@ -424,8 +424,8 @@ fn create(
|
|||||||
)?;
|
)?;
|
||||||
|
|
||||||
let created = ctx
|
let created = ctx
|
||||||
.db()
|
.query_manager()
|
||||||
.upsert_http_request(&request, &UpdateSource::Sync)
|
.with_tx(|tx| tx.upsert_http_request(&request, &UpdateSource::Sync))
|
||||||
.map_err(|e| format!("Failed to create request: {e}"))?;
|
.map_err(|e| format!("Failed to create request: {e}"))?;
|
||||||
|
|
||||||
println!("Created request: {}", created.id);
|
println!("Created request: {}", created.id);
|
||||||
@@ -443,8 +443,8 @@ fn create(
|
|||||||
}
|
}
|
||||||
|
|
||||||
let created = ctx
|
let created = ctx
|
||||||
.db()
|
.query_manager()
|
||||||
.upsert_http_request(&request, &UpdateSource::Sync)
|
.with_tx(|tx| tx.upsert_http_request(&request, &UpdateSource::Sync))
|
||||||
.map_err(|e| format!("Failed to create request: {e}"))?;
|
.map_err(|e| format!("Failed to create request: {e}"))?;
|
||||||
|
|
||||||
println!("Created request: {}", created.id);
|
println!("Created request: {}", created.id);
|
||||||
@@ -463,8 +463,8 @@ fn update(ctx: &CliContext, json: Option<String>, json_input: Option<String>) ->
|
|||||||
let updated = apply_merge_patch(&existing, &patch, &id, "request update")?;
|
let updated = apply_merge_patch(&existing, &patch, &id, "request update")?;
|
||||||
|
|
||||||
let saved = ctx
|
let saved = ctx
|
||||||
.db()
|
.query_manager()
|
||||||
.upsert_http_request(&updated, &UpdateSource::Sync)
|
.with_tx(|tx| tx.upsert_http_request(&updated, &UpdateSource::Sync))
|
||||||
.map_err(|e| format!("Failed to update request: {e}"))?;
|
.map_err(|e| format!("Failed to update request: {e}"))?;
|
||||||
|
|
||||||
println!("Updated request: {}", saved.id);
|
println!("Updated request: {}", saved.id);
|
||||||
@@ -487,8 +487,8 @@ fn delete(ctx: &CliContext, request_id: &str, yes: bool) -> CommandResult {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let deleted = ctx
|
let deleted = ctx
|
||||||
.db()
|
.query_manager()
|
||||||
.delete_http_request_by_id(request_id, &UpdateSource::Sync)
|
.with_tx(|tx| tx.delete_http_request_by_id(request_id, &UpdateSource::Sync))
|
||||||
.map_err(|e| format!("Failed to delete request: {e}"))?;
|
.map_err(|e| format!("Failed to delete request: {e}"))?;
|
||||||
println!("Deleted request: {}", deleted.id);
|
println!("Deleted request: {}", deleted.id);
|
||||||
Ok(())
|
Ok(())
|
||||||
|
|||||||
@@ -118,8 +118,8 @@ fn delete(ctx: &CliContext, id: &str, yes: bool) -> CommandResult {
|
|||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
let count = ctx
|
let count = ctx
|
||||||
.db()
|
.query_manager()
|
||||||
.delete_all_http_responses_for_request(id, &UpdateSource::Sync)
|
.with_tx(|tx| tx.delete_all_http_responses_for_request(id, &UpdateSource::Sync))
|
||||||
.map_err(|e| format!("Failed to delete responses: {e}"))?;
|
.map_err(|e| format!("Failed to delete responses: {e}"))?;
|
||||||
println!("Deleted {count} responses for request {id}");
|
println!("Deleted {count} responses for request {id}");
|
||||||
return Ok(());
|
return Ok(());
|
||||||
@@ -131,8 +131,10 @@ fn delete(ctx: &CliContext, id: &str, yes: bool) -> CommandResult {
|
|||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
let count = ctx
|
let count = ctx
|
||||||
.db()
|
.query_manager()
|
||||||
.delete_all_http_responses_for_workspace(&workspace_id, &UpdateSource::Sync)
|
.with_tx(|tx| {
|
||||||
|
tx.delete_all_http_responses_for_workspace(&workspace_id, &UpdateSource::Sync)
|
||||||
|
})
|
||||||
.map_err(|e| format!("Failed to delete responses: {e}"))?;
|
.map_err(|e| format!("Failed to delete responses: {e}"))?;
|
||||||
println!("Deleted {count} responses for workspace {workspace_id}");
|
println!("Deleted {count} responses for workspace {workspace_id}");
|
||||||
Ok(())
|
Ok(())
|
||||||
|
|||||||
@@ -84,8 +84,8 @@ fn create(
|
|||||||
.map_err(|e| format!("Failed to parse workspace create JSON: {e}"))?;
|
.map_err(|e| format!("Failed to parse workspace create JSON: {e}"))?;
|
||||||
|
|
||||||
let created = ctx
|
let created = ctx
|
||||||
.db()
|
.query_manager()
|
||||||
.upsert_workspace(&workspace, &UpdateSource::Sync)
|
.with_tx(|tx| tx.upsert_workspace(&workspace, &UpdateSource::Sync))
|
||||||
.map_err(|e| format!("Failed to create workspace: {e}"))?;
|
.map_err(|e| format!("Failed to create workspace: {e}"))?;
|
||||||
println!("Created workspace: {}", created.id);
|
println!("Created workspace: {}", created.id);
|
||||||
return Ok(());
|
return Ok(());
|
||||||
@@ -97,8 +97,8 @@ fn create(
|
|||||||
|
|
||||||
let workspace = Workspace { name, ..Default::default() };
|
let workspace = Workspace { name, ..Default::default() };
|
||||||
let created = ctx
|
let created = ctx
|
||||||
.db()
|
.query_manager()
|
||||||
.upsert_workspace(&workspace, &UpdateSource::Sync)
|
.with_tx(|tx| tx.upsert_workspace(&workspace, &UpdateSource::Sync))
|
||||||
.map_err(|e| format!("Failed to create workspace: {e}"))?;
|
.map_err(|e| format!("Failed to create workspace: {e}"))?;
|
||||||
println!("Created workspace: {}", created.id);
|
println!("Created workspace: {}", created.id);
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -115,8 +115,8 @@ fn update(ctx: &CliContext, json: Option<String>, json_input: Option<String>) ->
|
|||||||
let updated = apply_merge_patch(&existing, &patch, &id, "workspace update")?;
|
let updated = apply_merge_patch(&existing, &patch, &id, "workspace update")?;
|
||||||
|
|
||||||
let saved = ctx
|
let saved = ctx
|
||||||
.db()
|
.query_manager()
|
||||||
.upsert_workspace(&updated, &UpdateSource::Sync)
|
.with_tx(|tx| tx.upsert_workspace(&updated, &UpdateSource::Sync))
|
||||||
.map_err(|e| format!("Failed to update workspace: {e}"))?;
|
.map_err(|e| format!("Failed to update workspace: {e}"))?;
|
||||||
|
|
||||||
println!("Updated workspace: {}", saved.id);
|
println!("Updated workspace: {}", saved.id);
|
||||||
@@ -130,8 +130,10 @@ fn delete(ctx: &CliContext, workspace_id: &str, yes: bool) -> CommandResult {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let deleted = ctx
|
let deleted = ctx
|
||||||
.db()
|
.query_manager()
|
||||||
.delete_workspace_by_id(workspace_id, &UpdateSource::Sync, ctx.blob_manager())
|
.with_tx(|tx| {
|
||||||
|
tx.delete_workspace_by_id(workspace_id, &UpdateSource::Sync, ctx.blob_manager())
|
||||||
|
})
|
||||||
.map_err(|e| format!("Failed to delete workspace: {e}"))?;
|
.map_err(|e| format!("Failed to delete workspace: {e}"))?;
|
||||||
println!("Deleted workspace: {}", deleted.id);
|
println!("Deleted workspace: {}", deleted.id);
|
||||||
Ok(())
|
Ok(())
|
||||||
|
|||||||
@@ -51,11 +51,9 @@ impl CliContext {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// Guest: the desktop may have this DB open, so only what's safe beside a live session
|
// Guest: the desktop may have this DB open, so only what's safe beside a live session
|
||||||
let _ = yaak_lifecycle::on_launch(
|
let _ = query_manager.with_tx(|tx| {
|
||||||
&yaak_lifecycle::Host::guest(),
|
yaak_lifecycle::on_launch(&yaak_lifecycle::Host::guest(), tx, &blob_manager)
|
||||||
&query_manager.connect(),
|
});
|
||||||
&blob_manager,
|
|
||||||
);
|
|
||||||
|
|
||||||
let encryption_manager = Arc::new(EncryptionManager::new(query_manager.clone(), app_id));
|
let encryption_manager = Arc::new(EncryptionManager::new(query_manager.clone(), app_id));
|
||||||
|
|
||||||
|
|||||||
@@ -13,7 +13,6 @@ use tokio::task::JoinHandle;
|
|||||||
use yaak::plugin_events::{
|
use yaak::plugin_events::{
|
||||||
GroupedPluginEvent, HostRequest, SharedPluginEventContext, handle_shared_plugin_event,
|
GroupedPluginEvent, HostRequest, SharedPluginEventContext, handle_shared_plugin_event,
|
||||||
};
|
};
|
||||||
use yaak_models::render::{render_grpc_request, render_http_request};
|
|
||||||
use yaak::response_body::FileResponseBodyStore;
|
use yaak::response_body::FileResponseBodyStore;
|
||||||
use yaak::send::{SendHttpRequestWithPluginsParams, send_http_request_with_plugins};
|
use yaak::send::{SendHttpRequestWithPluginsParams, send_http_request_with_plugins};
|
||||||
use yaak_crypto::manager::EncryptionManager;
|
use yaak_crypto::manager::EncryptionManager;
|
||||||
@@ -24,6 +23,7 @@ use yaak_models::models::Environment;
|
|||||||
use yaak_models::queries::any_request::AnyRequest;
|
use yaak_models::queries::any_request::AnyRequest;
|
||||||
use yaak_models::query_manager::QueryManager;
|
use yaak_models::query_manager::QueryManager;
|
||||||
use yaak_models::render::make_vars_hashmap;
|
use yaak_models::render::make_vars_hashmap;
|
||||||
|
use yaak_models::render::{render_grpc_request, render_http_request};
|
||||||
use yaak_models::util::UpdateSource;
|
use yaak_models::util::UpdateSource;
|
||||||
use yaak_plugins::events::{
|
use yaak_plugins::events::{
|
||||||
EmptyPayload, ErrorResponse, FormInput, GetCookieValueResponse, InternalEvent,
|
EmptyPayload, ErrorResponse, FormInput, GetCookieValueResponse, InternalEvent,
|
||||||
|
|||||||
@@ -40,8 +40,7 @@ pub fn seed_workspace(data_dir: &Path, workspace_id: &str) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
query_manager(data_dir)
|
query_manager(data_dir)
|
||||||
.connect()
|
.with_tx(|tx| tx.upsert_workspace(&workspace, &UpdateSource::Sync))
|
||||||
.upsert_workspace(&workspace, &UpdateSource::Sync)
|
|
||||||
.expect("Failed to seed workspace");
|
.expect("Failed to seed workspace");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -56,8 +55,7 @@ pub fn seed_request(data_dir: &Path, workspace_id: &str, request_id: &str) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
query_manager(data_dir)
|
query_manager(data_dir)
|
||||||
.connect()
|
.with_tx(|tx| tx.upsert_http_request(&request, &UpdateSource::Sync))
|
||||||
.upsert_http_request(&request, &UpdateSource::Sync)
|
|
||||||
.expect("Failed to seed request");
|
.expect("Failed to seed request");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -70,8 +68,7 @@ pub fn seed_folder(data_dir: &Path, workspace_id: &str, folder_id: &str) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
query_manager(data_dir)
|
query_manager(data_dir)
|
||||||
.connect()
|
.with_tx(|tx| tx.upsert_folder(&folder, &UpdateSource::Sync))
|
||||||
.upsert_folder(&folder, &UpdateSource::Sync)
|
|
||||||
.expect("Failed to seed folder");
|
.expect("Failed to seed folder");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -85,8 +82,7 @@ pub fn seed_grpc_request(data_dir: &Path, workspace_id: &str, request_id: &str)
|
|||||||
};
|
};
|
||||||
|
|
||||||
query_manager(data_dir)
|
query_manager(data_dir)
|
||||||
.connect()
|
.with_tx(|tx| tx.upsert_grpc_request(&request, &UpdateSource::Sync))
|
||||||
.upsert_grpc_request(&request, &UpdateSource::Sync)
|
|
||||||
.expect("Failed to seed gRPC request");
|
.expect("Failed to seed gRPC request");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -100,7 +96,6 @@ pub fn seed_websocket_request(data_dir: &Path, workspace_id: &str, request_id: &
|
|||||||
};
|
};
|
||||||
|
|
||||||
query_manager(data_dir)
|
query_manager(data_dir)
|
||||||
.connect()
|
.with_tx(|tx| tx.upsert_websocket_request(&request, &UpdateSource::Sync))
|
||||||
.upsert_websocket_request(&request, &UpdateSource::Sync)
|
|
||||||
.expect("Failed to seed WebSocket request");
|
.expect("Failed to seed WebSocket request");
|
||||||
}
|
}
|
||||||
@@ -4,6 +4,7 @@ use common::{cli_cmd, parse_created_id, query_manager, seed_request};
|
|||||||
use predicates::str::contains;
|
use predicates::str::contains;
|
||||||
use serde_json::Value;
|
use serde_json::Value;
|
||||||
use tempfile::TempDir;
|
use tempfile::TempDir;
|
||||||
|
use yaak_models::util::UpdateSource;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn export_writes_yaak_workspace_file() {
|
fn export_writes_yaak_workspace_file() {
|
||||||
@@ -160,8 +161,7 @@ fn import_postman_environment_uses_workspace_id() {
|
|||||||
|
|
||||||
let query_manager = query_manager(data_dir);
|
let query_manager = query_manager(data_dir);
|
||||||
let db = query_manager.connect();
|
let db = query_manager.connect();
|
||||||
let environments =
|
let environments = db.list_environments(&workspace_id).expect("list imported environments");
|
||||||
db.list_environments_ensure_base(&workspace_id).expect("list imported environments");
|
|
||||||
|
|
||||||
let imported_environment =
|
let imported_environment =
|
||||||
environments.iter().find(|e| e.name == "Local").expect("postman environment imported");
|
environments.iter().find(|e| e.name == "Local").expect("postman environment imported");
|
||||||
@@ -209,7 +209,10 @@ fn re_import_merges_into_linked_workspace() {
|
|||||||
],
|
],
|
||||||
);
|
);
|
||||||
cli_cmd(data_dir)
|
cli_cmd(data_dir)
|
||||||
.args(["import", import_path.to_str().expect("import path is utf-8")])
|
.args([
|
||||||
|
"import",
|
||||||
|
import_path.to_str().expect("import path is utf-8"),
|
||||||
|
])
|
||||||
.assert()
|
.assert()
|
||||||
.success()
|
.success()
|
||||||
.stdout(contains("Imported 1 workspace, 2 HTTP requests"));
|
.stdout(contains("Imported 1 workspace, 2 HTTP requests"));
|
||||||
@@ -257,3 +260,65 @@ fn re_import_merges_into_linked_workspace() {
|
|||||||
assert!(requests.iter().any(|r| r.name == "Request B"), "removal must not auto-apply");
|
assert!(requests.iter().any(|r| r.name == "Request B"), "removal must not auto-apply");
|
||||||
assert!(requests.iter().any(|r| r.name == "Request C"));
|
assert!(requests.iter().any(|r| r.name == "Request C"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn re_import_leaves_deleted_resources_alone() {
|
||||||
|
let temp_dir = TempDir::new().expect("Failed to create temp dir");
|
||||||
|
let data_dir = temp_dir.path();
|
||||||
|
let import_path = temp_dir.path().join("linked.json");
|
||||||
|
|
||||||
|
write_linked_fixture(
|
||||||
|
&import_path,
|
||||||
|
&[
|
||||||
|
("req_a", "Request A", "https://example.com/a"),
|
||||||
|
("req_b", "Request B", "https://example.com/b"),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
cli_cmd(data_dir)
|
||||||
|
.args([
|
||||||
|
"import",
|
||||||
|
import_path.to_str().expect("import path is utf-8"),
|
||||||
|
])
|
||||||
|
.assert()
|
||||||
|
.success();
|
||||||
|
|
||||||
|
let workspace_id = {
|
||||||
|
let query_manager = query_manager(data_dir);
|
||||||
|
let db = query_manager.connect();
|
||||||
|
let workspace_id = db
|
||||||
|
.list_workspaces()
|
||||||
|
.expect("list workspaces")
|
||||||
|
.into_iter()
|
||||||
|
.find(|w| w.name == "Linked Workspace")
|
||||||
|
.expect("workspace imported")
|
||||||
|
.id;
|
||||||
|
let request_b = db
|
||||||
|
.list_http_requests(&workspace_id)
|
||||||
|
.expect("list requests")
|
||||||
|
.into_iter()
|
||||||
|
.find(|r| r.name == "Request B")
|
||||||
|
.expect("request B imported");
|
||||||
|
drop(db);
|
||||||
|
query_manager
|
||||||
|
.with_tx(|tx| tx.delete_http_request_by_id(&request_b.id, &UpdateSource::Sync))
|
||||||
|
.expect("delete request B");
|
||||||
|
workspace_id
|
||||||
|
};
|
||||||
|
|
||||||
|
cli_cmd(data_dir)
|
||||||
|
.args([
|
||||||
|
"import",
|
||||||
|
import_path.to_str().expect("import path is utf-8"),
|
||||||
|
"--workspace-id",
|
||||||
|
&workspace_id,
|
||||||
|
])
|
||||||
|
.assert()
|
||||||
|
.success()
|
||||||
|
.stdout(contains("Skipped 1 ignored"));
|
||||||
|
|
||||||
|
let query_manager = query_manager(data_dir);
|
||||||
|
let requests =
|
||||||
|
query_manager.connect().list_http_requests(&workspace_id).expect("list requests");
|
||||||
|
assert_eq!(requests.len(), 1, "a deleted request must not come back: {requests:?}");
|
||||||
|
assert_eq!(requests[0].name, "Request A");
|
||||||
|
}
|
||||||
@@ -25,8 +25,7 @@ fn top_level_send_folder_sends_http_requests_and_prints_summary() {
|
|||||||
..Default::default()
|
..Default::default()
|
||||||
};
|
};
|
||||||
query_manager(data_dir)
|
query_manager(data_dir)
|
||||||
.connect()
|
.with_tx(|tx| tx.upsert_http_request(&request, &UpdateSource::Sync))
|
||||||
.upsert_http_request(&request, &UpdateSource::Sync)
|
|
||||||
.expect("Failed to seed folder request");
|
.expect("Failed to seed folder request");
|
||||||
|
|
||||||
cli_cmd(data_dir)
|
cli_cmd(data_dir)
|
||||||
|
|||||||
@@ -145,11 +145,8 @@ async fn cache_control(req: Request, next: Next) -> Response {
|
|||||||
.get(header::CONTENT_TYPE)
|
.get(header::CONTENT_TYPE)
|
||||||
.and_then(|v| v.to_str().ok())
|
.and_then(|v| v.to_str().ok())
|
||||||
.is_some_and(|v| v.starts_with("text/html"));
|
.is_some_and(|v| v.starts_with("text/html"));
|
||||||
let value = if hashed_name && !is_html {
|
let value =
|
||||||
"public, max-age=31536000, immutable"
|
if hashed_name && !is_html { "public, max-age=31536000, immutable" } else { "no-cache" };
|
||||||
} else {
|
|
||||||
"no-cache"
|
|
||||||
};
|
|
||||||
res.headers_mut().insert(header::CACHE_CONTROL, HeaderValue::from_static(value));
|
res.headers_mut().insert(header::CACHE_CONTROL, HeaderValue::from_static(value));
|
||||||
res
|
res
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -19,7 +19,6 @@ pub(crate) fn metadata_to_map(metadata: MetadataMap) -> BTreeMap<String, String>
|
|||||||
entries
|
entries
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
pub(crate) async fn build_metadata<R: Runtime>(
|
pub(crate) async fn build_metadata<R: Runtime>(
|
||||||
window: &WebviewWindow<R>,
|
window: &WebviewWindow<R>,
|
||||||
request: &GrpcRequest,
|
request: &GrpcRequest,
|
||||||
|
|||||||
@@ -177,4 +177,3 @@ async fn send_http_request_inner<R: Runtime>(
|
|||||||
|
|
||||||
Ok(SentHttpRequest { response: result.response, body: result.response_body })
|
Ok(SentHttpRequest { response: result.response, body: result.response_body })
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -29,16 +29,16 @@ use tokio::sync::Mutex;
|
|||||||
use tokio::task::block_in_place;
|
use tokio::task::block_in_place;
|
||||||
use tokio::time;
|
use tokio::time;
|
||||||
use yaak::send::ResponseBody;
|
use yaak::send::ResponseBody;
|
||||||
use yaak_commands::responses::locate_response_body;
|
|
||||||
use yaak_commands::resolve::resolve_grpc_request;
|
use yaak_commands::resolve::resolve_grpc_request;
|
||||||
|
use yaak_commands::responses::locate_response_body;
|
||||||
use yaak_common::command::new_checked_command;
|
use yaak_common::command::new_checked_command;
|
||||||
use yaak_crypto::manager::EncryptionManager;
|
use yaak_crypto::manager::EncryptionManager;
|
||||||
use yaak_grpc::manager::{GrpcConfig, GrpcHandle};
|
use yaak_grpc::manager::{GrpcConfig, GrpcHandle};
|
||||||
use yaak_grpc::{Code, ServiceDefinition};
|
use yaak_grpc::{Code, ServiceDefinition};
|
||||||
use yaak_mac_window::AppHandleMacWindowExt;
|
use yaak_mac_window::AppHandleMacWindowExt;
|
||||||
use yaak_models::models::{
|
use yaak_models::models::{
|
||||||
CookieJar, Environment, GrpcConnection, GrpcConnectionState, GrpcEvent,
|
CookieJar, Environment, GrpcConnection, GrpcConnectionState, GrpcEvent, GrpcEventType,
|
||||||
GrpcEventType, HttpRequest, HttpResponse, HttpResponseState, Workspace,
|
HttpRequest, HttpResponse, HttpResponseState, Workspace,
|
||||||
};
|
};
|
||||||
use yaak_models::util::{BatchUpsertResult, ImportDestination, ImportPlan, UpdateSource};
|
use yaak_models::util::{BatchUpsertResult, ImportDestination, ImportPlan, UpdateSource};
|
||||||
use yaak_plugins::events::{
|
use yaak_plugins::events::{
|
||||||
@@ -330,18 +330,20 @@ async fn cmd_grpc_go<R: Runtime>(
|
|||||||
let settings = app_handle.db().get_settings();
|
let settings = app_handle.db().get_settings();
|
||||||
let client_cert = find_client_certificate(&request.url, &settings.client_certificates);
|
let client_cert = find_client_certificate(&request.url, &settings.client_certificates);
|
||||||
|
|
||||||
let conn = app_handle.db().upsert_grpc_connection(
|
let conn = app_handle.with_tx(|tx| {
|
||||||
&GrpcConnection {
|
tx.upsert_grpc_connection(
|
||||||
workspace_id: request.workspace_id.clone(),
|
&GrpcConnection {
|
||||||
request_id: request.id.clone(),
|
workspace_id: request.workspace_id.clone(),
|
||||||
status: -1,
|
request_id: request.id.clone(),
|
||||||
elapsed: 0,
|
status: -1,
|
||||||
state: GrpcConnectionState::Initialized,
|
elapsed: 0,
|
||||||
url: request.url.clone(),
|
state: GrpcConnectionState::Initialized,
|
||||||
..Default::default()
|
url: request.url.clone(),
|
||||||
},
|
..Default::default()
|
||||||
&UpdateSource::from_window_label(window.label()),
|
},
|
||||||
)?;
|
&UpdateSource::from_window_label(window.label()),
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
|
||||||
let conn_id = conn.id.clone();
|
let conn_id = conn.id.clone();
|
||||||
|
|
||||||
@@ -386,15 +388,17 @@ async fn cmd_grpc_go<R: Runtime>(
|
|||||||
let connection = match connection {
|
let connection = match connection {
|
||||||
Ok(c) => c,
|
Ok(c) => c,
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
app_handle.db().upsert_grpc_connection(
|
app_handle.with_tx(|tx| {
|
||||||
&GrpcConnection {
|
tx.upsert_grpc_connection(
|
||||||
elapsed: start.elapsed().as_millis() as i32,
|
&GrpcConnection {
|
||||||
error: Some(err.to_string()),
|
elapsed: start.elapsed().as_millis() as i32,
|
||||||
state: GrpcConnectionState::Closed,
|
error: Some(err.to_string()),
|
||||||
..conn.clone()
|
state: GrpcConnectionState::Closed,
|
||||||
},
|
..conn.clone()
|
||||||
&UpdateSource::from_window_label(window.label()),
|
},
|
||||||
)?;
|
&UpdateSource::from_window_label(window.label()),
|
||||||
|
)
|
||||||
|
})?;
|
||||||
return Ok(conn_id);
|
return Ok(conn_id);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -495,15 +499,17 @@ async fn cmd_grpc_go<R: Runtime>(
|
|||||||
.await?;
|
.await?;
|
||||||
let msg = strip_json_comments(&msg);
|
let msg = strip_json_comments(&msg);
|
||||||
|
|
||||||
app_handle.db().upsert_grpc_event(
|
app_handle.with_tx(|tx| {
|
||||||
&GrpcEvent {
|
tx.upsert_grpc_event(
|
||||||
content: format!("Connecting to {}", req.url),
|
&GrpcEvent {
|
||||||
event_type: GrpcEventType::ConnectionStart,
|
content: format!("Connecting to {}", req.url),
|
||||||
metadata: metadata.clone(),
|
event_type: GrpcEventType::ConnectionStart,
|
||||||
..base_event.clone()
|
metadata: metadata.clone(),
|
||||||
},
|
..base_event.clone()
|
||||||
&UpdateSource::from_window_label(window.label()),
|
},
|
||||||
)?;
|
&UpdateSource::from_window_label(window.label()),
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
|
||||||
async move {
|
async move {
|
||||||
// Create callback for streaming methods that handles both success and error
|
// Create callback for streaming methods that handles both success and error
|
||||||
@@ -513,24 +519,28 @@ async fn cmd_grpc_go<R: Runtime>(
|
|||||||
let window_label = window.label().to_string();
|
let window_label = window.label().to_string();
|
||||||
move |result: std::result::Result<String, String>| match result {
|
move |result: std::result::Result<String, String>| match result {
|
||||||
Ok(msg) => {
|
Ok(msg) => {
|
||||||
let _ = app_handle.db().upsert_grpc_event(
|
let _ = app_handle.with_tx(|tx| {
|
||||||
&GrpcEvent {
|
tx.upsert_grpc_event(
|
||||||
content: msg,
|
&GrpcEvent {
|
||||||
event_type: GrpcEventType::ClientMessage,
|
content: msg,
|
||||||
..base_event.clone()
|
event_type: GrpcEventType::ClientMessage,
|
||||||
},
|
..base_event.clone()
|
||||||
&UpdateSource::from_window_label(&window_label),
|
},
|
||||||
);
|
&UpdateSource::from_window_label(&window_label),
|
||||||
|
)
|
||||||
|
});
|
||||||
}
|
}
|
||||||
Err(error) => {
|
Err(error) => {
|
||||||
let _ = app_handle.db().upsert_grpc_event(
|
let _ = app_handle.with_tx(|tx| {
|
||||||
&GrpcEvent {
|
tx.upsert_grpc_event(
|
||||||
content: format!("Failed to send message: {}", error),
|
&GrpcEvent {
|
||||||
event_type: GrpcEventType::Error,
|
content: format!("Failed to send message: {}", error),
|
||||||
..base_event.clone()
|
event_type: GrpcEventType::Error,
|
||||||
},
|
..base_event.clone()
|
||||||
&UpdateSource::from_window_label(&window_label),
|
},
|
||||||
);
|
&UpdateSource::from_window_label(&window_label),
|
||||||
|
)
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -583,36 +593,38 @@ async fn cmd_grpc_go<R: Runtime>(
|
|||||||
|
|
||||||
if !method_desc.is_client_streaming() {
|
if !method_desc.is_client_streaming() {
|
||||||
app_handle
|
app_handle
|
||||||
.db()
|
.with_tx(|tx| {
|
||||||
.upsert_grpc_event(
|
tx.upsert_grpc_event(
|
||||||
&GrpcEvent {
|
&GrpcEvent {
|
||||||
event_type: GrpcEventType::ClientMessage,
|
event_type: GrpcEventType::ClientMessage,
|
||||||
content: msg,
|
content: msg,
|
||||||
..base_event.clone()
|
..base_event.clone()
|
||||||
},
|
},
|
||||||
&UpdateSource::from_window_label(window.label()),
|
&UpdateSource::from_window_label(window.label()),
|
||||||
)
|
)
|
||||||
|
})
|
||||||
.unwrap();
|
.unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
match maybe_msg {
|
match maybe_msg {
|
||||||
Some(Ok(msg)) => {
|
Some(Ok(msg)) => {
|
||||||
app_handle
|
app_handle
|
||||||
.db()
|
.with_tx(|tx| {
|
||||||
.upsert_grpc_event(
|
tx.upsert_grpc_event(
|
||||||
&GrpcEvent {
|
&GrpcEvent {
|
||||||
metadata: metadata_to_map(msg.metadata().clone()),
|
metadata: metadata_to_map(msg.metadata().clone()),
|
||||||
content: if msg.metadata().len() == 0 {
|
content: if msg.metadata().len() == 0 {
|
||||||
"Received response"
|
"Received response"
|
||||||
} else {
|
} else {
|
||||||
"Received response with metadata"
|
"Received response with metadata"
|
||||||
}
|
}
|
||||||
.to_string(),
|
.to_string(),
|
||||||
event_type: GrpcEventType::Info,
|
event_type: GrpcEventType::Info,
|
||||||
..base_event.clone()
|
..base_event.clone()
|
||||||
},
|
},
|
||||||
&UpdateSource::from_window_label(window.label()),
|
&UpdateSource::from_window_label(window.label()),
|
||||||
)
|
)
|
||||||
|
})
|
||||||
.unwrap();
|
.unwrap();
|
||||||
let response_message = msg.into_inner();
|
let response_message = msg.into_inner();
|
||||||
let content = match connection
|
let content = match connection
|
||||||
@@ -622,83 +634,88 @@ async fn cmd_grpc_go<R: Runtime>(
|
|||||||
Ok(content) => content,
|
Ok(content) => content,
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
app_handle
|
app_handle
|
||||||
.db()
|
.with_tx(|tx| {
|
||||||
.upsert_grpc_event(
|
tx.upsert_grpc_event(
|
||||||
&GrpcEvent {
|
&GrpcEvent {
|
||||||
content: "Failed to read response".to_string(),
|
content: "Failed to read response".to_string(),
|
||||||
error: Some(err.to_string()),
|
error: Some(err.to_string()),
|
||||||
status: Some(Code::Internal as i32),
|
status: Some(Code::Internal as i32),
|
||||||
event_type: GrpcEventType::ConnectionEnd,
|
event_type: GrpcEventType::ConnectionEnd,
|
||||||
..base_event.clone()
|
..base_event.clone()
|
||||||
},
|
},
|
||||||
&UpdateSource::from_window_label(window.label()),
|
&UpdateSource::from_window_label(window.label()),
|
||||||
)
|
)
|
||||||
|
})
|
||||||
.unwrap();
|
.unwrap();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
app_handle
|
app_handle
|
||||||
.db()
|
.with_tx(|tx| {
|
||||||
.upsert_grpc_event(
|
tx.upsert_grpc_event(
|
||||||
&GrpcEvent {
|
&GrpcEvent {
|
||||||
content,
|
content,
|
||||||
event_type: GrpcEventType::ServerMessage,
|
event_type: GrpcEventType::ServerMessage,
|
||||||
..base_event.clone()
|
..base_event.clone()
|
||||||
},
|
},
|
||||||
&UpdateSource::from_window_label(window.label()),
|
&UpdateSource::from_window_label(window.label()),
|
||||||
)
|
)
|
||||||
|
})
|
||||||
.unwrap();
|
.unwrap();
|
||||||
app_handle
|
app_handle
|
||||||
.db()
|
.with_tx(|tx| {
|
||||||
.upsert_grpc_event(
|
tx.upsert_grpc_event(
|
||||||
&GrpcEvent {
|
&GrpcEvent {
|
||||||
content: "Connection complete".to_string(),
|
content: "Connection complete".to_string(),
|
||||||
event_type: GrpcEventType::ConnectionEnd,
|
event_type: GrpcEventType::ConnectionEnd,
|
||||||
status: Some(Code::Ok as i32),
|
status: Some(Code::Ok as i32),
|
||||||
..base_event.clone()
|
..base_event.clone()
|
||||||
},
|
},
|
||||||
&UpdateSource::from_window_label(window.label()),
|
&UpdateSource::from_window_label(window.label()),
|
||||||
)
|
)
|
||||||
|
})
|
||||||
.unwrap();
|
.unwrap();
|
||||||
}
|
}
|
||||||
Some(Err(yaak_grpc::error::Error::GrpcStreamError(e))) => {
|
Some(Err(yaak_grpc::error::Error::GrpcStreamError(e))) => {
|
||||||
app_handle
|
app_handle
|
||||||
.db()
|
.with_tx(|tx| {
|
||||||
.upsert_grpc_event(
|
tx.upsert_grpc_event(
|
||||||
&(match e.status {
|
&(match e.status {
|
||||||
Some(s) => GrpcEvent {
|
Some(s) => GrpcEvent {
|
||||||
error: Some(s.message().to_string()),
|
error: Some(s.message().to_string()),
|
||||||
status: Some(s.code() as i32),
|
status: Some(s.code() as i32),
|
||||||
content: "Request failed".to_string(),
|
content: "Request failed".to_string(),
|
||||||
metadata: metadata_to_map(s.metadata().clone()),
|
metadata: metadata_to_map(s.metadata().clone()),
|
||||||
event_type: GrpcEventType::ConnectionEnd,
|
event_type: GrpcEventType::ConnectionEnd,
|
||||||
..base_event.clone()
|
..base_event.clone()
|
||||||
},
|
},
|
||||||
None => GrpcEvent {
|
None => GrpcEvent {
|
||||||
error: Some(e.message),
|
error: Some(e.message),
|
||||||
|
status: Some(Code::Unknown as i32),
|
||||||
|
content: "Request failed".to_string(),
|
||||||
|
event_type: GrpcEventType::ConnectionEnd,
|
||||||
|
..base_event.clone()
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
&UpdateSource::from_window_label(window.label()),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
Some(Err(e)) => {
|
||||||
|
app_handle
|
||||||
|
.with_tx(|tx| {
|
||||||
|
tx.upsert_grpc_event(
|
||||||
|
&GrpcEvent {
|
||||||
|
error: Some(e.to_string()),
|
||||||
status: Some(Code::Unknown as i32),
|
status: Some(Code::Unknown as i32),
|
||||||
content: "Request failed".to_string(),
|
content: "Request failed".to_string(),
|
||||||
event_type: GrpcEventType::ConnectionEnd,
|
event_type: GrpcEventType::ConnectionEnd,
|
||||||
..base_event.clone()
|
..base_event.clone()
|
||||||
},
|
},
|
||||||
}),
|
&UpdateSource::from_window_label(window.label()),
|
||||||
&UpdateSource::from_window_label(window.label()),
|
)
|
||||||
)
|
})
|
||||||
.unwrap();
|
|
||||||
}
|
|
||||||
Some(Err(e)) => {
|
|
||||||
app_handle
|
|
||||||
.db()
|
|
||||||
.upsert_grpc_event(
|
|
||||||
&GrpcEvent {
|
|
||||||
error: Some(e.to_string()),
|
|
||||||
status: Some(Code::Unknown as i32),
|
|
||||||
content: "Request failed".to_string(),
|
|
||||||
event_type: GrpcEventType::ConnectionEnd,
|
|
||||||
..base_event.clone()
|
|
||||||
},
|
|
||||||
&UpdateSource::from_window_label(window.label()),
|
|
||||||
)
|
|
||||||
.unwrap();
|
.unwrap();
|
||||||
}
|
}
|
||||||
None => {
|
None => {
|
||||||
@@ -709,64 +726,67 @@ async fn cmd_grpc_go<R: Runtime>(
|
|||||||
let mut stream = match maybe_stream {
|
let mut stream = match maybe_stream {
|
||||||
Some(Ok(stream)) => {
|
Some(Ok(stream)) => {
|
||||||
app_handle
|
app_handle
|
||||||
.db()
|
.with_tx(|tx| {
|
||||||
.upsert_grpc_event(
|
tx.upsert_grpc_event(
|
||||||
&GrpcEvent {
|
&GrpcEvent {
|
||||||
metadata: metadata_to_map(stream.metadata().clone()),
|
metadata: metadata_to_map(stream.metadata().clone()),
|
||||||
content: if stream.metadata().len() == 0 {
|
content: if stream.metadata().len() == 0 {
|
||||||
"Received response"
|
"Received response"
|
||||||
} else {
|
} else {
|
||||||
"Received response with metadata"
|
"Received response with metadata"
|
||||||
}
|
}
|
||||||
.to_string(),
|
.to_string(),
|
||||||
event_type: GrpcEventType::Info,
|
event_type: GrpcEventType::Info,
|
||||||
..base_event.clone()
|
..base_event.clone()
|
||||||
},
|
},
|
||||||
&UpdateSource::from_window_label(window.label()),
|
&UpdateSource::from_window_label(window.label()),
|
||||||
)
|
)
|
||||||
|
})
|
||||||
.unwrap();
|
.unwrap();
|
||||||
stream.into_inner()
|
stream.into_inner()
|
||||||
}
|
}
|
||||||
Some(Err(yaak_grpc::error::Error::GrpcStreamError(e))) => {
|
Some(Err(yaak_grpc::error::Error::GrpcStreamError(e))) => {
|
||||||
warn!("GRPC stream error {e:?}");
|
warn!("GRPC stream error {e:?}");
|
||||||
app_handle
|
app_handle
|
||||||
.db()
|
.with_tx(|tx| {
|
||||||
.upsert_grpc_event(
|
tx.upsert_grpc_event(
|
||||||
&(match e.status {
|
&(match e.status {
|
||||||
Some(s) => GrpcEvent {
|
Some(s) => GrpcEvent {
|
||||||
error: Some(s.message().to_string()),
|
error: Some(s.message().to_string()),
|
||||||
status: Some(s.code() as i32),
|
status: Some(s.code() as i32),
|
||||||
content: "Stream failed".to_string(),
|
content: "Stream failed".to_string(),
|
||||||
metadata: metadata_to_map(s.metadata().clone()),
|
metadata: metadata_to_map(s.metadata().clone()),
|
||||||
event_type: GrpcEventType::ConnectionEnd,
|
event_type: GrpcEventType::ConnectionEnd,
|
||||||
..base_event.clone()
|
..base_event.clone()
|
||||||
},
|
},
|
||||||
None => GrpcEvent {
|
None => GrpcEvent {
|
||||||
error: Some(e.message),
|
error: Some(e.message),
|
||||||
status: Some(Code::Unknown as i32),
|
status: Some(Code::Unknown as i32),
|
||||||
content: "Stream failed".to_string(),
|
content: "Stream failed".to_string(),
|
||||||
event_type: GrpcEventType::ConnectionEnd,
|
event_type: GrpcEventType::ConnectionEnd,
|
||||||
..base_event.clone()
|
..base_event.clone()
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
&UpdateSource::from_window_label(window.label()),
|
&UpdateSource::from_window_label(window.label()),
|
||||||
)
|
)
|
||||||
|
})
|
||||||
.unwrap();
|
.unwrap();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
Some(Err(e)) => {
|
Some(Err(e)) => {
|
||||||
app_handle
|
app_handle
|
||||||
.db()
|
.with_tx(|tx| {
|
||||||
.upsert_grpc_event(
|
tx.upsert_grpc_event(
|
||||||
&GrpcEvent {
|
&GrpcEvent {
|
||||||
error: Some(e.to_string()),
|
error: Some(e.to_string()),
|
||||||
status: Some(Code::Unknown as i32),
|
status: Some(Code::Unknown as i32),
|
||||||
content: "Stream failed".to_string(),
|
content: "Stream failed".to_string(),
|
||||||
event_type: GrpcEventType::ConnectionEnd,
|
event_type: GrpcEventType::ConnectionEnd,
|
||||||
..base_event.clone()
|
..base_event.clone()
|
||||||
},
|
},
|
||||||
&UpdateSource::from_window_label(window.label()),
|
&UpdateSource::from_window_label(window.label()),
|
||||||
)
|
)
|
||||||
|
})
|
||||||
.unwrap();
|
.unwrap();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -783,65 +803,69 @@ async fn cmd_grpc_go<R: Runtime>(
|
|||||||
Ok(message) => message,
|
Ok(message) => message,
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
app_handle
|
app_handle
|
||||||
.db()
|
.with_tx(|tx| {
|
||||||
.upsert_grpc_event(
|
tx.upsert_grpc_event(
|
||||||
&GrpcEvent {
|
&GrpcEvent {
|
||||||
content: "Failed to read response".to_string(),
|
content: "Failed to read response".to_string(),
|
||||||
error: Some(err.to_string()),
|
error: Some(err.to_string()),
|
||||||
status: Some(Code::Internal as i32),
|
status: Some(Code::Internal as i32),
|
||||||
event_type: GrpcEventType::ConnectionEnd,
|
event_type: GrpcEventType::ConnectionEnd,
|
||||||
..base_event.clone()
|
..base_event.clone()
|
||||||
},
|
},
|
||||||
&UpdateSource::from_window_label(window.label()),
|
&UpdateSource::from_window_label(window.label()),
|
||||||
)
|
)
|
||||||
|
})
|
||||||
.unwrap();
|
.unwrap();
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
app_handle
|
app_handle
|
||||||
.db()
|
.with_tx(|tx| {
|
||||||
.upsert_grpc_event(
|
tx.upsert_grpc_event(
|
||||||
&GrpcEvent {
|
&GrpcEvent {
|
||||||
content: message,
|
content: message,
|
||||||
event_type: GrpcEventType::ServerMessage,
|
event_type: GrpcEventType::ServerMessage,
|
||||||
..base_event.clone()
|
..base_event.clone()
|
||||||
},
|
},
|
||||||
&UpdateSource::from_window_label(window.label()),
|
&UpdateSource::from_window_label(window.label()),
|
||||||
)
|
)
|
||||||
|
})
|
||||||
.unwrap();
|
.unwrap();
|
||||||
}
|
}
|
||||||
Ok(None) => {
|
Ok(None) => {
|
||||||
let trailers =
|
let trailers =
|
||||||
stream.trailers().await.unwrap_or_default().unwrap_or_default();
|
stream.trailers().await.unwrap_or_default().unwrap_or_default();
|
||||||
app_handle
|
app_handle
|
||||||
.db()
|
.with_tx(|tx| {
|
||||||
.upsert_grpc_event(
|
tx.upsert_grpc_event(
|
||||||
&GrpcEvent {
|
&GrpcEvent {
|
||||||
content: "Connection complete".to_string(),
|
content: "Connection complete".to_string(),
|
||||||
status: Some(Code::Ok as i32),
|
status: Some(Code::Ok as i32),
|
||||||
metadata: metadata_to_map(trailers),
|
metadata: metadata_to_map(trailers),
|
||||||
event_type: GrpcEventType::ConnectionEnd,
|
event_type: GrpcEventType::ConnectionEnd,
|
||||||
..base_event.clone()
|
..base_event.clone()
|
||||||
},
|
},
|
||||||
&UpdateSource::from_window_label(window.label()),
|
&UpdateSource::from_window_label(window.label()),
|
||||||
)
|
)
|
||||||
|
})
|
||||||
.unwrap();
|
.unwrap();
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
Err(status) => {
|
Err(status) => {
|
||||||
app_handle
|
app_handle
|
||||||
.db()
|
.with_tx(|tx| {
|
||||||
.upsert_grpc_event(
|
tx.upsert_grpc_event(
|
||||||
&GrpcEvent {
|
&GrpcEvent {
|
||||||
content: "Stream failed".to_string(),
|
content: "Stream failed".to_string(),
|
||||||
error: Some(status.message().to_string()),
|
error: Some(status.message().to_string()),
|
||||||
status: Some(status.code() as i32),
|
status: Some(status.code() as i32),
|
||||||
metadata: metadata_to_map(status.metadata().clone()),
|
metadata: metadata_to_map(status.metadata().clone()),
|
||||||
event_type: GrpcEventType::ConnectionEnd,
|
event_type: GrpcEventType::ConnectionEnd,
|
||||||
..base_event.clone()
|
..base_event.clone()
|
||||||
},
|
},
|
||||||
&UpdateSource::from_window_label(window.label()),
|
&UpdateSource::from_window_label(window.label()),
|
||||||
)
|
)
|
||||||
|
})
|
||||||
.unwrap();
|
.unwrap();
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
@@ -874,21 +898,24 @@ async fn cmd_grpc_go<R: Runtime>(
|
|||||||
}).unwrap();
|
}).unwrap();
|
||||||
},
|
},
|
||||||
_ = cancelled_rx.changed() => {
|
_ = cancelled_rx.changed() => {
|
||||||
w.db().upsert_grpc_event(
|
w.with_tx(|tx| {
|
||||||
&GrpcEvent {
|
tx.upsert_grpc_event(
|
||||||
content: "Cancelled".to_string(),
|
&GrpcEvent {
|
||||||
event_type: GrpcEventType::ConnectionEnd,
|
content: "Cancelled".to_string(),
|
||||||
status: Some(Code::Cancelled as i32),
|
event_type: GrpcEventType::ConnectionEnd,
|
||||||
..base_msg.clone()
|
status: Some(Code::Cancelled as i32),
|
||||||
},
|
..base_msg.clone()
|
||||||
&UpdateSource::from_window_label(window.label()),
|
},
|
||||||
).unwrap();
|
&UpdateSource::from_window_label(window.label()),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
w.with_tx(|c| {
|
w.with_tx(|c| {
|
||||||
c.upsert_grpc_connection(
|
c.upsert_grpc_connection(
|
||||||
&GrpcConnection{
|
&GrpcConnection{
|
||||||
elapsed: start.elapsed().as_millis() as i32,
|
elapsed: start.elapsed().as_millis() as i32,
|
||||||
status: Code::Cancelled as i32,
|
status: Code::Cancelled as i32,
|
||||||
state: GrpcConnectionState::Closed,
|
state: GrpcConnectionState::Closed,
|
||||||
..c.get_grpc_connection( &conn_id).unwrap().clone()
|
..c.get_grpc_connection( &conn_id).unwrap().clone()
|
||||||
},
|
},
|
||||||
&UpdateSource::from_window_label(window.label()),
|
&UpdateSource::from_window_label(window.label()),
|
||||||
@@ -1033,20 +1060,6 @@ async fn cmd_commit_import<R: Runtime>(
|
|||||||
commit_import(&window, plan)
|
commit_import(&window, plan)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
/// Decodes base64 and writes the bytes to a file the user picked.
|
/// Decodes base64 and writes the bytes to a file the user picked.
|
||||||
///
|
///
|
||||||
/// The webview can't do this itself: its `fs` permissions are read-only and scoped to the app
|
/// The webview can't do this itself: its `fs` permissions are read-only and scoped to the app
|
||||||
@@ -1080,15 +1093,17 @@ async fn cmd_send_http_request<R: Runtime>(
|
|||||||
let request = app_handle.db().get_http_request(&request_id)?;
|
let request = app_handle.db().get_http_request(&request_id)?;
|
||||||
|
|
||||||
let blobs = app_handle.blob_manager();
|
let blobs = app_handle.blob_manager();
|
||||||
let response = app_handle.db().upsert_http_response(
|
let response = app_handle.with_tx(|tx| {
|
||||||
&HttpResponse {
|
tx.upsert_http_response(
|
||||||
request_id: request.id.clone(),
|
&HttpResponse {
|
||||||
workspace_id: request.workspace_id.clone(),
|
request_id: request.id.clone(),
|
||||||
..Default::default()
|
workspace_id: request.workspace_id.clone(),
|
||||||
},
|
..Default::default()
|
||||||
&UpdateSource::from_window_label(window.label()),
|
},
|
||||||
&blobs,
|
&UpdateSource::from_window_label(window.label()),
|
||||||
)?;
|
&blobs,
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
|
||||||
let (cancel_tx, mut cancel_rx) = tokio::sync::watch::channel(false);
|
let (cancel_tx, mut cancel_rx) = tokio::sync::watch::channel(false);
|
||||||
app_handle.listen_any(format!("cancel_http_response_{}", response.id), move |_event| {
|
app_handle.listen_any(format!("cancel_http_response_{}", response.id), move |_event| {
|
||||||
@@ -1126,22 +1141,23 @@ async fn cmd_send_http_request<R: Runtime>(
|
|||||||
Ok(sent) => sent.response,
|
Ok(sent) => sent.response,
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
let resp = app_handle.db().get_http_response(&response.id)?;
|
let resp = app_handle.db().get_http_response(&response.id)?;
|
||||||
app_handle.db().upsert_http_response(
|
app_handle.with_tx(|tx| {
|
||||||
&HttpResponse {
|
tx.upsert_http_response(
|
||||||
state: HttpResponseState::Closed,
|
&HttpResponse {
|
||||||
error: Some(e.to_string()),
|
state: HttpResponseState::Closed,
|
||||||
..resp
|
error: Some(e.to_string()),
|
||||||
},
|
..resp
|
||||||
&UpdateSource::from_window_label(window.label()),
|
},
|
||||||
&blobs,
|
&UpdateSource::from_window_label(window.label()),
|
||||||
)?
|
&blobs,
|
||||||
|
)
|
||||||
|
})?
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
Ok(r)
|
Ok(r)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
async fn cmd_new_child_window<R: Runtime>(
|
async fn cmd_new_child_window<R: Runtime>(
|
||||||
parent_window: WebviewWindow<R>,
|
parent_window: WebviewWindow<R>,
|
||||||
url: &str,
|
url: &str,
|
||||||
@@ -1269,8 +1285,8 @@ pub fn run() {
|
|||||||
.setup(|app| {
|
.setup(|app| {
|
||||||
let lifecycle_host = yaak_lifecycle::Host::owner()
|
let lifecycle_host = yaak_lifecycle::Host::owner()
|
||||||
.with_responses_dir(app.path().app_data_dir()?.join("responses"));
|
.with_responses_dir(app.path().app_data_dir()?.join("responses"));
|
||||||
if let Err(e) =
|
if let Err(e) = app
|
||||||
yaak_lifecycle::on_launch(&lifecycle_host, &app.db(), &app.blob_manager())
|
.with_tx(|tx| yaak_lifecycle::on_launch(&lifecycle_host, tx, &app.blob_manager()))
|
||||||
{
|
{
|
||||||
error!("on_launch hook failed: {e:?}");
|
error!("on_launch hook failed: {e:?}");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ use tauri::plugin::TauriPlugin;
|
|||||||
use tauri::{Emitter, Manager, Runtime, State};
|
use tauri::{Emitter, Manager, Runtime, State};
|
||||||
use tauri_plugin_dialog::{DialogExt, MessageDialogKind};
|
use tauri_plugin_dialog::{DialogExt, MessageDialogKind};
|
||||||
use yaak_models::blob_manager::BlobManager;
|
use yaak_models::blob_manager::BlobManager;
|
||||||
use yaak_models::client_db::ClientDb;
|
use yaak_models::client_db::{ClientDb, WriteDb};
|
||||||
use yaak_models::error::Result;
|
use yaak_models::error::Result;
|
||||||
use yaak_models::query_manager::QueryManager;
|
use yaak_models::query_manager::QueryManager;
|
||||||
use yaak_models::util::{ModelPayload, UpdateSource};
|
use yaak_models::util::{ModelPayload, UpdateSource};
|
||||||
@@ -95,7 +95,7 @@ pub trait QueryManagerExt<'a, R> {
|
|||||||
fn db(&'a self) -> ClientDb<'a>;
|
fn db(&'a self) -> ClientDb<'a>;
|
||||||
fn with_tx<F, T>(&'a self, func: F) -> Result<T>
|
fn with_tx<F, T>(&'a self, func: F) -> Result<T>
|
||||||
where
|
where
|
||||||
F: FnOnce(&ClientDb) -> Result<T>;
|
F: FnOnce(&WriteDb) -> Result<T>;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a, R: Runtime, M: Manager<R>> QueryManagerExt<'a, R> for M {
|
impl<'a, R: Runtime, M: Manager<R>> QueryManagerExt<'a, R> for M {
|
||||||
@@ -110,7 +110,7 @@ impl<'a, R: Runtime, M: Manager<R>> QueryManagerExt<'a, R> for M {
|
|||||||
|
|
||||||
fn with_tx<F, T>(&'a self, func: F) -> Result<T>
|
fn with_tx<F, T>(&'a self, func: F) -> Result<T>
|
||||||
where
|
where
|
||||||
F: FnOnce(&ClientDb) -> Result<T>,
|
F: FnOnce(&WriteDb) -> Result<T>,
|
||||||
{
|
{
|
||||||
let qm = self.state::<QueryManager>();
|
let qm = self.state::<QueryManager>();
|
||||||
qm.inner().with_tx(func)
|
qm.inner().with_tx(func)
|
||||||
|
|||||||
@@ -55,12 +55,15 @@ impl YaakNotifier {
|
|||||||
seen.push(id.to_string());
|
seen.push(id.to_string());
|
||||||
debug!("Marked notification as seen {}", id);
|
debug!("Marked notification as seen {}", id);
|
||||||
let seen_json = serde_json::to_string(&seen)?;
|
let seen_json = serde_json::to_string(&seen)?;
|
||||||
window.db().set_key_value_raw(
|
window.with_tx(|tx| {
|
||||||
KV_NAMESPACE,
|
tx.set_key_value_raw(
|
||||||
KV_KEY,
|
KV_NAMESPACE,
|
||||||
seen_json.as_str(),
|
KV_KEY,
|
||||||
&UpdateSource::from_window_label(window.label()),
|
seen_json.as_str(),
|
||||||
);
|
&UpdateSource::from_window_label(window.label()),
|
||||||
|
);
|
||||||
|
Ok(())
|
||||||
|
})?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -111,7 +111,7 @@ async fn handle_host_plugin_request<R: Runtime>(
|
|||||||
}
|
}
|
||||||
|
|
||||||
let new_plugin = Plugin { updated_at: Utc::now().naive_utc(), ..plugin };
|
let new_plugin = Plugin { updated_at: Utc::now().naive_utc(), ..plugin };
|
||||||
app_handle.db().upsert_plugin(&new_plugin, &UpdateSource::Plugin)?;
|
app_handle.with_tx(|tx| tx.upsert_plugin(&new_plugin, &UpdateSource::Plugin))?;
|
||||||
}
|
}
|
||||||
|
|
||||||
if !req.silent {
|
if !req.silent {
|
||||||
@@ -294,15 +294,17 @@ async fn handle_host_plugin_request<R: Runtime>(
|
|||||||
HttpResponse::default()
|
HttpResponse::default()
|
||||||
} else {
|
} else {
|
||||||
let blobs = window.blob_manager();
|
let blobs = window.blob_manager();
|
||||||
window.db().upsert_http_response(
|
window.with_tx(|tx| {
|
||||||
&HttpResponse {
|
tx.upsert_http_response(
|
||||||
request_id: http_request.id.clone(),
|
&HttpResponse {
|
||||||
workspace_id: http_request.workspace_id.clone(),
|
request_id: http_request.id.clone(),
|
||||||
..Default::default()
|
workspace_id: http_request.workspace_id.clone(),
|
||||||
},
|
..Default::default()
|
||||||
&UpdateSource::from_window_label(window.label()),
|
},
|
||||||
&blobs,
|
&UpdateSource::from_window_label(window.label()),
|
||||||
)?
|
&blobs,
|
||||||
|
)
|
||||||
|
})?
|
||||||
};
|
};
|
||||||
|
|
||||||
let http_response = send_http_request_with_context(
|
let http_response = send_http_request_with_context(
|
||||||
|
|||||||
@@ -16,8 +16,7 @@ use std::time::{Duration, Instant};
|
|||||||
use tauri::path::BaseDirectory;
|
use tauri::path::BaseDirectory;
|
||||||
use tauri::plugin::{Builder, TauriPlugin};
|
use tauri::plugin::{Builder, TauriPlugin};
|
||||||
use tauri::{
|
use tauri::{
|
||||||
AppHandle, Emitter, Manager, RunEvent, Runtime, State, WebviewWindow, WindowEvent,
|
AppHandle, Emitter, Manager, RunEvent, Runtime, State, WebviewWindow, WindowEvent, is_dev,
|
||||||
is_dev,
|
|
||||||
};
|
};
|
||||||
use tokio::sync::Mutex;
|
use tokio::sync::Mutex;
|
||||||
use ts_rs::TS;
|
use ts_rs::TS;
|
||||||
@@ -28,10 +27,10 @@ use yaak_plugins::api::{
|
|||||||
PluginNameVersion, PluginSearchResponse, PluginUpdatesResponse, check_plugin_updates,
|
PluginNameVersion, PluginSearchResponse, PluginUpdatesResponse, check_plugin_updates,
|
||||||
search_plugins,
|
search_plugins,
|
||||||
};
|
};
|
||||||
|
use yaak_plugins::error::Error::PluginErr;
|
||||||
use yaak_plugins::events::{Color, PluginContext, ShowToastRequest};
|
use yaak_plugins::events::{Color, PluginContext, ShowToastRequest};
|
||||||
use yaak_plugins::install::{delete_and_uninstall, download_and_install};
|
use yaak_plugins::install::{delete_and_uninstall, download_and_install};
|
||||||
use yaak_plugins::manager::PluginManager;
|
use yaak_plugins::manager::PluginManager;
|
||||||
use yaak_plugins::error::Error::PluginErr;
|
|
||||||
use yaak_plugins::plugin_meta::get_plugin_meta;
|
use yaak_plugins::plugin_meta::get_plugin_meta;
|
||||||
|
|
||||||
static EXITING: AtomicBool = AtomicBool::new(false);
|
static EXITING: AtomicBool = AtomicBool::new(false);
|
||||||
@@ -203,16 +202,18 @@ pub async fn cmd_plugins_install_from_directory<R: Runtime>(
|
|||||||
// Resolve the manager before writing the row so startup's plugin snapshot
|
// Resolve the manager before writing the row so startup's plugin snapshot
|
||||||
// can't include it and boot it a second time
|
// can't include it and boot it a second time
|
||||||
let plugin_manager = Arc::new(plugin_manager(&window).await?);
|
let plugin_manager = Arc::new(plugin_manager(&window).await?);
|
||||||
let plugin = window.db().upsert_plugin(
|
let plugin = window.with_tx(|tx| {
|
||||||
&Plugin {
|
tx.upsert_plugin(
|
||||||
directory: directory.into(),
|
&Plugin {
|
||||||
url: None,
|
directory: directory.into(),
|
||||||
enabled: true,
|
url: None,
|
||||||
source: PluginSource::Filesystem,
|
enabled: true,
|
||||||
..Default::default()
|
source: PluginSource::Filesystem,
|
||||||
},
|
..Default::default()
|
||||||
&UpdateSource::from_window_label(window.label()),
|
},
|
||||||
)?;
|
&UpdateSource::from_window_label(window.label()),
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
|
||||||
plugin_manager.add_plugin(&window.plugin_context(), &plugin).await?;
|
plugin_manager.add_plugin(&window.plugin_context(), &plugin).await?;
|
||||||
|
|
||||||
@@ -355,9 +356,11 @@ pub fn init<R: Runtime>() -> TauriPlugin<R> {
|
|||||||
),
|
),
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
.unwrap_or_else(|_| Err(yaak_plugins::error::Error::PluginErr(
|
.unwrap_or_else(|_| {
|
||||||
"Timed out starting the plugin runtime".to_string(),
|
Err(yaak_plugins::error::Error::PluginErr(
|
||||||
)));
|
"Timed out starting the plugin runtime".to_string(),
|
||||||
|
))
|
||||||
|
});
|
||||||
|
|
||||||
let manager = match result {
|
let manager = match result {
|
||||||
Ok(manager) => manager,
|
Ok(manager) => manager,
|
||||||
|
|||||||
@@ -4,5 +4,5 @@
|
|||||||
//! `yaak-commands` when the template commands did. Callers in this crate do not
|
//! `yaak-commands` when the template commands did. Callers in this crate do not
|
||||||
//! need to track which is which.
|
//! need to track which is which.
|
||||||
|
|
||||||
pub use yaak_models::render::{render_grpc_request, render_http_request};
|
|
||||||
pub use yaak_commands::render::{render_json_value, render_template};
|
pub use yaak_commands::render::{render_json_value, render_template};
|
||||||
|
pub use yaak_models::render::{render_grpc_request, render_http_request};
|
||||||
@@ -21,9 +21,9 @@ use crate::notifications::YaakNotifier;
|
|||||||
use crate::updates::YaakUpdater;
|
use crate::updates::YaakUpdater;
|
||||||
use log::warn;
|
use log::warn;
|
||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
use tauri::{Manager, Runtime, State, WebviewWindow};
|
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
use tauri::{Manager, Runtime, State, WebviewWindow};
|
||||||
use tokio::sync::Mutex;
|
use tokio::sync::Mutex;
|
||||||
use yaak_commands::{Host, PluginHost};
|
use yaak_commands::{Host, PluginHost};
|
||||||
use yaak_core::WorkspaceContext;
|
use yaak_core::WorkspaceContext;
|
||||||
@@ -32,8 +32,8 @@ use yaak_git::{
|
|||||||
BranchDeleteResult, CloneResult, GitBranchInfo, GitCommit, GitFileDiff, GitRemote,
|
BranchDeleteResult, CloneResult, GitBranchInfo, GitCommit, GitFileDiff, GitRemote,
|
||||||
GitStatusSummary, GitWorktreeStatus, PullResult, PushResult,
|
GitStatusSummary, GitWorktreeStatus, PullResult, PushResult,
|
||||||
};
|
};
|
||||||
use yaak_grpc::manager::GrpcHandle;
|
|
||||||
use yaak_grpc::ServiceDefinition;
|
use yaak_grpc::ServiceDefinition;
|
||||||
|
use yaak_grpc::manager::GrpcHandle;
|
||||||
use yaak_models::blob_manager::BlobManager;
|
use yaak_models::blob_manager::BlobManager;
|
||||||
use yaak_models::models::{
|
use yaak_models::models::{
|
||||||
GraphQlIntrospection, GrpcEvent, HttpRequest, HttpRequestHeader, HttpResponse,
|
GraphQlIntrospection, GrpcEvent, HttpRequest, HttpRequestHeader, HttpResponse,
|
||||||
@@ -42,26 +42,26 @@ use yaak_models::models::{
|
|||||||
};
|
};
|
||||||
use yaak_models::query_manager::QueryManager;
|
use yaak_models::query_manager::QueryManager;
|
||||||
use yaak_models::util::{BatchUpsertResult, ImportPlan};
|
use yaak_models::util::{BatchUpsertResult, ImportPlan};
|
||||||
|
use yaak_plugins::api::{PluginNameVersion, PluginSearchResponse, PluginUpdatesResponse};
|
||||||
use yaak_plugins::events::{
|
use yaak_plugins::events::{
|
||||||
CallFolderActionRequest, CallGrpcRequestActionRequest, CallHttpRequestActionRequest,
|
CallFolderActionRequest, CallGrpcRequestActionRequest, CallHttpRequestActionRequest,
|
||||||
CallWebsocketRequestActionRequest, CallWorkspaceActionRequest, FilterResponse, ImportResponse,
|
CallWebsocketRequestActionRequest, CallWorkspaceActionRequest, FilterResponse,
|
||||||
JsonPrimitive, RenderPurpose, GetFolderActionsResponse, GetGrpcRequestActionsResponse,
|
GetFolderActionsResponse, GetGrpcRequestActionsResponse, GetHttpAuthenticationConfigResponse,
|
||||||
GetHttpAuthenticationConfigResponse, GetHttpAuthenticationSummaryResponse,
|
GetHttpAuthenticationSummaryResponse, GetHttpRequestActionsResponse,
|
||||||
GetHttpRequestActionsResponse, GetTemplateFunctionConfigResponse,
|
GetTemplateFunctionConfigResponse, GetTemplateFunctionSummaryResponse, GetThemesResponse,
|
||||||
GetTemplateFunctionSummaryResponse, GetThemesResponse, GetWebsocketRequestActionsResponse,
|
GetWebsocketRequestActionsResponse, GetWorkspaceActionsResponse, ImportResponse, JsonPrimitive,
|
||||||
GetWorkspaceActionsResponse,
|
RenderPurpose,
|
||||||
};
|
};
|
||||||
use yaak_plugins::api::{PluginNameVersion, PluginSearchResponse, PluginUpdatesResponse};
|
|
||||||
use yaak_plugins::manager::PluginManager;
|
use yaak_plugins::manager::PluginManager;
|
||||||
use yaak_plugins::native_template_functions::encrypt_secure_template_function;
|
use yaak_plugins::native_template_functions::encrypt_secure_template_function;
|
||||||
use yaak_plugins::template_callback::PluginTemplateCallback;
|
|
||||||
use yaak_plugins::plugin_meta::PluginMetadata;
|
use yaak_plugins::plugin_meta::PluginMetadata;
|
||||||
|
use yaak_plugins::template_callback::PluginTemplateCallback;
|
||||||
use yaak_rpc::RpcRouter;
|
use yaak_rpc::RpcRouter;
|
||||||
use yaak_rpc_schema::*;
|
use yaak_rpc_schema::*;
|
||||||
use yaak_sse::sse::ServerSentEvent;
|
use yaak_sse::sse::ServerSentEvent;
|
||||||
use yaak_sync::sync::SyncOp;
|
use yaak_sync::sync::SyncOp;
|
||||||
use yaak_templates::TemplateCallback;
|
|
||||||
use yaak_tauri_utils::window::WorkspaceWindowTrait;
|
use yaak_tauri_utils::window::WorkspaceWindowTrait;
|
||||||
|
use yaak_templates::TemplateCallback;
|
||||||
use yaak_ws::WebsocketManager;
|
use yaak_ws::WebsocketManager;
|
||||||
|
|
||||||
/// Per-call context: the window a command was invoked from.
|
/// Per-call context: the window a command was invoked from.
|
||||||
@@ -231,17 +231,15 @@ impl<R: Runtime> PluginHost for ClientCtx<R> {
|
|||||||
Ok(self.pm().await?.call_workspace_action(&self.plugin_context(), req).await?)
|
Ok(self.pm().await?.call_workspace_action(&self.plugin_context(), req).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn call_folder_action(
|
async fn call_folder_action(&self, req: CallFolderActionRequest) -> yaak_commands::Result<()> {
|
||||||
&self,
|
|
||||||
req: CallFolderActionRequest,
|
|
||||||
) -> yaak_commands::Result<()> {
|
|
||||||
Ok(self.pm().await?.call_folder_action(&self.plugin_context(), req).await?)
|
Ok(self.pm().await?.call_folder_action(&self.plugin_context(), req).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn http_authentication_summaries(
|
async fn http_authentication_summaries(
|
||||||
&self,
|
&self,
|
||||||
) -> yaak_commands::Result<Vec<GetHttpAuthenticationSummaryResponse>> {
|
) -> yaak_commands::Result<Vec<GetHttpAuthenticationSummaryResponse>> {
|
||||||
let results = self.pm().await?.get_http_authentication_summaries(&self.plugin_context()).await?;
|
let results =
|
||||||
|
self.pm().await?.get_http_authentication_summaries(&self.plugin_context()).await?;
|
||||||
Ok(results.into_iter().map(|(_, a)| a).collect())
|
Ok(results.into_iter().map(|(_, a)| a).collect())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -393,11 +391,17 @@ async fn cmd_metadata<R: Runtime>(ctx: ClientCtx<R>, _req: CmdMetadataReq) -> Re
|
|||||||
Ok(crate::cmd_metadata(ctx.window.app_handle().clone()).await?)
|
Ok(crate::cmd_metadata(ctx.window.app_handle().clone()).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_template_tokens_to_string<R: Runtime>(ctx: ClientCtx<R>, req: CmdTemplateTokensToStringReq) -> Result<String> {
|
async fn cmd_template_tokens_to_string<R: Runtime>(
|
||||||
|
ctx: ClientCtx<R>,
|
||||||
|
req: CmdTemplateTokensToStringReq,
|
||||||
|
) -> Result<String> {
|
||||||
Ok(yaak_commands::templates::cmd_template_tokens_to_string(ctx, req).await?)
|
Ok(yaak_commands::templates::cmd_template_tokens_to_string(ctx, req).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_render_template<R: Runtime>(ctx: ClientCtx<R>, req: CmdRenderTemplateReq) -> Result<String> {
|
async fn cmd_render_template<R: Runtime>(
|
||||||
|
ctx: ClientCtx<R>,
|
||||||
|
req: CmdRenderTemplateReq,
|
||||||
|
) -> Result<String> {
|
||||||
Ok(yaak_commands::templates::cmd_render_template(ctx, req).await?)
|
Ok(yaak_commands::templates::cmd_render_template(ctx, req).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -405,55 +409,114 @@ async fn cmd_send_feedback<R: Runtime>(ctx: ClientCtx<R>, req: CmdSendFeedbackRe
|
|||||||
Ok(crate::cmd_send_feedback(ctx.window.app_handle().clone(), req.feature, req.text).await?)
|
Ok(crate::cmd_send_feedback(ctx.window.app_handle().clone(), req.feature, req.text).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_dismiss_notification<R: Runtime>(ctx: ClientCtx<R>, req: CmdDismissNotificationReq) -> Result<()> {
|
async fn cmd_dismiss_notification<R: Runtime>(
|
||||||
Ok(crate::cmd_dismiss_notification(ctx.window.clone(), &req.notification_id, ctx.window.app_handle().state::<Mutex<YaakNotifier>>()).await?)
|
ctx: ClientCtx<R>,
|
||||||
|
req: CmdDismissNotificationReq,
|
||||||
|
) -> Result<()> {
|
||||||
|
Ok(crate::cmd_dismiss_notification(
|
||||||
|
ctx.window.clone(),
|
||||||
|
&req.notification_id,
|
||||||
|
ctx.window.app_handle().state::<Mutex<YaakNotifier>>(),
|
||||||
|
)
|
||||||
|
.await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_grpc_reflect<R: Runtime>(ctx: ClientCtx<R>, req: CmdGrpcReflectReq) -> Result<Vec<ServiceDefinition>> {
|
async fn cmd_grpc_reflect<R: Runtime>(
|
||||||
Ok(crate::cmd_grpc_reflect(&req.request_id, req.environment_id.as_deref(), req.proto_files, ctx.window.clone(), ctx.window.app_handle().clone(), ctx.window.app_handle().state::<Mutex<GrpcHandle>>()).await?)
|
ctx: ClientCtx<R>,
|
||||||
|
req: CmdGrpcReflectReq,
|
||||||
|
) -> Result<Vec<ServiceDefinition>> {
|
||||||
|
Ok(crate::cmd_grpc_reflect(
|
||||||
|
&req.request_id,
|
||||||
|
req.environment_id.as_deref(),
|
||||||
|
req.proto_files,
|
||||||
|
ctx.window.clone(),
|
||||||
|
ctx.window.app_handle().clone(),
|
||||||
|
ctx.window.app_handle().state::<Mutex<GrpcHandle>>(),
|
||||||
|
)
|
||||||
|
.await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_grpc_go<R: Runtime>(ctx: ClientCtx<R>, req: CmdGrpcGoReq) -> Result<String> {
|
async fn cmd_grpc_go<R: Runtime>(ctx: ClientCtx<R>, req: CmdGrpcGoReq) -> Result<String> {
|
||||||
Ok(crate::cmd_grpc_go(&req.request_id, req.environment_id.as_deref(), req.proto_files, ctx.window.app_handle().clone(), ctx.window.clone(), ctx.window.app_handle().state::<Mutex<GrpcHandle>>()).await?)
|
Ok(crate::cmd_grpc_go(
|
||||||
|
&req.request_id,
|
||||||
|
req.environment_id.as_deref(),
|
||||||
|
req.proto_files,
|
||||||
|
ctx.window.app_handle().clone(),
|
||||||
|
ctx.window.clone(),
|
||||||
|
ctx.window.app_handle().state::<Mutex<GrpcHandle>>(),
|
||||||
|
)
|
||||||
|
.await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_restart<R: Runtime>(ctx: ClientCtx<R>, _req: CmdRestartReq) -> Result<()> {
|
async fn cmd_restart<R: Runtime>(ctx: ClientCtx<R>, _req: CmdRestartReq) -> Result<()> {
|
||||||
Ok(crate::cmd_restart(ctx.window.app_handle().clone()).await?)
|
Ok(crate::cmd_restart(ctx.window.app_handle().clone()).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_send_ephemeral_request<R: Runtime>(ctx: ClientCtx<R>, req: CmdSendEphemeralRequestReq) -> Result<EphemeralHttpResponse> {
|
async fn cmd_send_ephemeral_request<R: Runtime>(
|
||||||
Ok(crate::cmd_send_ephemeral_request(req.request, req.environment_id.as_deref(), req.cookie_jar_id.as_deref(), ctx.window.clone(), ctx.window.app_handle().clone()).await?)
|
ctx: ClientCtx<R>,
|
||||||
|
req: CmdSendEphemeralRequestReq,
|
||||||
|
) -> Result<EphemeralHttpResponse> {
|
||||||
|
Ok(crate::cmd_send_ephemeral_request(
|
||||||
|
req.request,
|
||||||
|
req.environment_id.as_deref(),
|
||||||
|
req.cookie_jar_id.as_deref(),
|
||||||
|
ctx.window.clone(),
|
||||||
|
ctx.window.app_handle().clone(),
|
||||||
|
)
|
||||||
|
.await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_format_json<R: Runtime>(ctx: ClientCtx<R>, req: CmdFormatJsonReq) -> Result<String> {
|
async fn cmd_format_json<R: Runtime>(ctx: ClientCtx<R>, req: CmdFormatJsonReq) -> Result<String> {
|
||||||
Ok(yaak_commands::data::cmd_format_json(ctx, req).await?)
|
Ok(yaak_commands::data::cmd_format_json(ctx, req).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_format_graphql<R: Runtime>(_ctx: ClientCtx<R>, req: CmdFormatGraphqlReq) -> Result<String> {
|
async fn cmd_format_graphql<R: Runtime>(
|
||||||
|
_ctx: ClientCtx<R>,
|
||||||
|
req: CmdFormatGraphqlReq,
|
||||||
|
) -> Result<String> {
|
||||||
Ok(crate::cmd_format_graphql(&req.text).await?)
|
Ok(crate::cmd_format_graphql(&req.text).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_http_response_body<R: Runtime>(ctx: ClientCtx<R>, req: CmdHttpResponseBodyReq) -> Result<FilterResponse> {
|
async fn cmd_http_response_body<R: Runtime>(
|
||||||
Ok(crate::cmd_http_response_body(ctx.window.clone(), &req.response_id, req.filter.as_deref()).await?)
|
ctx: ClientCtx<R>,
|
||||||
|
req: CmdHttpResponseBodyReq,
|
||||||
|
) -> Result<FilterResponse> {
|
||||||
|
Ok(crate::cmd_http_response_body(ctx.window.clone(), &req.response_id, req.filter.as_deref())
|
||||||
|
.await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_http_response_body_path<R: Runtime>(ctx: ClientCtx<R>, req: CmdHttpResponseBodyPathReq) -> Result<Option<String>> {
|
async fn cmd_http_response_body_path<R: Runtime>(
|
||||||
|
ctx: ClientCtx<R>,
|
||||||
|
req: CmdHttpResponseBodyPathReq,
|
||||||
|
) -> Result<Option<String>> {
|
||||||
Ok(yaak_commands::responses::cmd_http_response_body_path(ctx, req).await?)
|
Ok(yaak_commands::responses::cmd_http_response_body_path(ctx, req).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_http_request_body<R: Runtime>(ctx: ClientCtx<R>, req: CmdHttpRequestBodyReq) -> Result<Option<Vec<u8>>> {
|
async fn cmd_http_request_body<R: Runtime>(
|
||||||
|
ctx: ClientCtx<R>,
|
||||||
|
req: CmdHttpRequestBodyReq,
|
||||||
|
) -> Result<Option<Vec<u8>>> {
|
||||||
Ok(yaak_commands::responses::cmd_http_request_body(ctx, req).await?)
|
Ok(yaak_commands::responses::cmd_http_request_body(ctx, req).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_get_sse_events<R: Runtime>(ctx: ClientCtx<R>, req: CmdGetSseEventsReq) -> Result<Vec<ServerSentEvent>> {
|
async fn cmd_get_sse_events<R: Runtime>(
|
||||||
|
ctx: ClientCtx<R>,
|
||||||
|
req: CmdGetSseEventsReq,
|
||||||
|
) -> Result<Vec<ServerSentEvent>> {
|
||||||
Ok(crate::cmd_get_sse_events(ctx.window.app_handle().clone(), &req.response_id).await?)
|
Ok(crate::cmd_get_sse_events(ctx.window.app_handle().clone(), &req.response_id).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_get_http_response_events<R: Runtime>(ctx: ClientCtx<R>, req: CmdGetHttpResponseEventsReq) -> Result<Vec<HttpResponseEvent>> {
|
async fn cmd_get_http_response_events<R: Runtime>(
|
||||||
|
ctx: ClientCtx<R>,
|
||||||
|
req: CmdGetHttpResponseEventsReq,
|
||||||
|
) -> Result<Vec<HttpResponseEvent>> {
|
||||||
Ok(yaak_commands::responses::cmd_get_http_response_events(ctx, req).await?)
|
Ok(yaak_commands::responses::cmd_get_http_response_events(ctx, req).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_import_data<R: Runtime>(ctx: ClientCtx<R>, req: CmdImportDataReq) -> Result<ImportPlan> {
|
async fn cmd_import_data<R: Runtime>(
|
||||||
|
ctx: ClientCtx<R>,
|
||||||
|
req: CmdImportDataReq,
|
||||||
|
) -> Result<ImportPlan> {
|
||||||
Ok(crate::cmd_import_data(ctx.window.clone(), &req.file_path, req.destination).await?)
|
Ok(crate::cmd_import_data(ctx.window.clone(), &req.file_path, req.destination).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -461,16 +524,25 @@ async fn cmd_import_url<R: Runtime>(ctx: ClientCtx<R>, req: CmdImportUrlReq) ->
|
|||||||
Ok(crate::cmd_import_url(ctx.window.clone(), &req.url, req.destination).await?)
|
Ok(crate::cmd_import_url(ctx.window.clone(), &req.url, req.destination).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_commit_import<R: Runtime>(ctx: ClientCtx<R>, req: CmdCommitImportReq) -> Result<BatchUpsertResult> {
|
async fn cmd_commit_import<R: Runtime>(
|
||||||
|
ctx: ClientCtx<R>,
|
||||||
|
req: CmdCommitImportReq,
|
||||||
|
) -> Result<BatchUpsertResult> {
|
||||||
Ok(crate::cmd_commit_import(ctx.window.clone(), req.plan).await?)
|
Ok(crate::cmd_commit_import(ctx.window.clone(), req.plan).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_list_import_sources<R: Runtime>(ctx: ClientCtx<R>, req: CmdListImportSourcesReq) -> Result<Vec<ImportSource>> {
|
async fn cmd_list_import_sources<R: Runtime>(
|
||||||
|
ctx: ClientCtx<R>,
|
||||||
|
req: CmdListImportSourcesReq,
|
||||||
|
) -> Result<Vec<ImportSource>> {
|
||||||
use crate::models_ext::QueryManagerExt;
|
use crate::models_ext::QueryManagerExt;
|
||||||
Ok(ctx.window.db().list_import_sources(&req.workspace_id)?)
|
Ok(ctx.window.db().list_import_sources(&req.workspace_id)?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_import_sources_for_origin<R: Runtime>(ctx: ClientCtx<R>, req: CmdImportSourcesForOriginReq) -> Result<Vec<ImportSource>> {
|
async fn cmd_import_sources_for_origin<R: Runtime>(
|
||||||
|
ctx: ClientCtx<R>,
|
||||||
|
req: CmdImportSourcesForOriginReq,
|
||||||
|
) -> Result<Vec<ImportSource>> {
|
||||||
use crate::models_ext::QueryManagerExt;
|
use crate::models_ext::QueryManagerExt;
|
||||||
let origin = match (req.file_path, req.url) {
|
let origin = match (req.file_path, req.url) {
|
||||||
(Some(file_path), _) => crate::import::file_origin(&file_path).origin,
|
(Some(file_path), _) => crate::import::file_origin(&file_path).origin,
|
||||||
@@ -483,67 +555,115 @@ async fn cmd_import_sources_for_origin<R: Runtime>(ctx: ClientCtx<R>, req: CmdIm
|
|||||||
Ok(ctx.window.db().list_import_sources_by_origin(&origin)?)
|
Ok(ctx.window.db().list_import_sources_by_origin(&origin)?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_http_request_actions<R: Runtime>(ctx: ClientCtx<R>, req: CmdHttpRequestActionsReq) -> Result<Vec<GetHttpRequestActionsResponse>> {
|
async fn cmd_http_request_actions<R: Runtime>(
|
||||||
|
ctx: ClientCtx<R>,
|
||||||
|
req: CmdHttpRequestActionsReq,
|
||||||
|
) -> Result<Vec<GetHttpRequestActionsResponse>> {
|
||||||
Ok(yaak_commands::actions::cmd_http_request_actions(ctx, req).await?)
|
Ok(yaak_commands::actions::cmd_http_request_actions(ctx, req).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_websocket_request_actions<R: Runtime>(ctx: ClientCtx<R>, req: CmdWebsocketRequestActionsReq) -> Result<Vec<GetWebsocketRequestActionsResponse>> {
|
async fn cmd_websocket_request_actions<R: Runtime>(
|
||||||
|
ctx: ClientCtx<R>,
|
||||||
|
req: CmdWebsocketRequestActionsReq,
|
||||||
|
) -> Result<Vec<GetWebsocketRequestActionsResponse>> {
|
||||||
Ok(yaak_commands::actions::cmd_websocket_request_actions(ctx, req).await?)
|
Ok(yaak_commands::actions::cmd_websocket_request_actions(ctx, req).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_call_websocket_request_action<R: Runtime>(ctx: ClientCtx<R>, req: CmdCallWebsocketRequestActionReq) -> Result<()> {
|
async fn cmd_call_websocket_request_action<R: Runtime>(
|
||||||
|
ctx: ClientCtx<R>,
|
||||||
|
req: CmdCallWebsocketRequestActionReq,
|
||||||
|
) -> Result<()> {
|
||||||
Ok(yaak_commands::actions::cmd_call_websocket_request_action(ctx, req).await?)
|
Ok(yaak_commands::actions::cmd_call_websocket_request_action(ctx, req).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_workspace_actions<R: Runtime>(ctx: ClientCtx<R>, req: CmdWorkspaceActionsReq) -> Result<Vec<GetWorkspaceActionsResponse>> {
|
async fn cmd_workspace_actions<R: Runtime>(
|
||||||
|
ctx: ClientCtx<R>,
|
||||||
|
req: CmdWorkspaceActionsReq,
|
||||||
|
) -> Result<Vec<GetWorkspaceActionsResponse>> {
|
||||||
Ok(yaak_commands::actions::cmd_workspace_actions(ctx, req).await?)
|
Ok(yaak_commands::actions::cmd_workspace_actions(ctx, req).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_call_workspace_action<R: Runtime>(ctx: ClientCtx<R>, req: CmdCallWorkspaceActionReq) -> Result<()> {
|
async fn cmd_call_workspace_action<R: Runtime>(
|
||||||
|
ctx: ClientCtx<R>,
|
||||||
|
req: CmdCallWorkspaceActionReq,
|
||||||
|
) -> Result<()> {
|
||||||
Ok(yaak_commands::actions::cmd_call_workspace_action(ctx, req).await?)
|
Ok(yaak_commands::actions::cmd_call_workspace_action(ctx, req).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_folder_actions<R: Runtime>(ctx: ClientCtx<R>, req: CmdFolderActionsReq) -> Result<Vec<GetFolderActionsResponse>> {
|
async fn cmd_folder_actions<R: Runtime>(
|
||||||
|
ctx: ClientCtx<R>,
|
||||||
|
req: CmdFolderActionsReq,
|
||||||
|
) -> Result<Vec<GetFolderActionsResponse>> {
|
||||||
Ok(yaak_commands::actions::cmd_folder_actions(ctx, req).await?)
|
Ok(yaak_commands::actions::cmd_folder_actions(ctx, req).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_call_folder_action<R: Runtime>(ctx: ClientCtx<R>, req: CmdCallFolderActionReq) -> Result<()> {
|
async fn cmd_call_folder_action<R: Runtime>(
|
||||||
|
ctx: ClientCtx<R>,
|
||||||
|
req: CmdCallFolderActionReq,
|
||||||
|
) -> Result<()> {
|
||||||
Ok(yaak_commands::actions::cmd_call_folder_action(ctx, req).await?)
|
Ok(yaak_commands::actions::cmd_call_folder_action(ctx, req).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_grpc_request_actions<R: Runtime>(ctx: ClientCtx<R>, req: CmdGrpcRequestActionsReq) -> Result<Vec<GetGrpcRequestActionsResponse>> {
|
async fn cmd_grpc_request_actions<R: Runtime>(
|
||||||
|
ctx: ClientCtx<R>,
|
||||||
|
req: CmdGrpcRequestActionsReq,
|
||||||
|
) -> Result<Vec<GetGrpcRequestActionsResponse>> {
|
||||||
Ok(yaak_commands::actions::cmd_grpc_request_actions(ctx, req).await?)
|
Ok(yaak_commands::actions::cmd_grpc_request_actions(ctx, req).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_template_function_summaries<R: Runtime>(ctx: ClientCtx<R>, req: CmdTemplateFunctionSummariesReq) -> Result<Vec<GetTemplateFunctionSummaryResponse>> {
|
async fn cmd_template_function_summaries<R: Runtime>(
|
||||||
|
ctx: ClientCtx<R>,
|
||||||
|
req: CmdTemplateFunctionSummariesReq,
|
||||||
|
) -> Result<Vec<GetTemplateFunctionSummaryResponse>> {
|
||||||
Ok(yaak_commands::templates::cmd_template_function_summaries(ctx, req).await?)
|
Ok(yaak_commands::templates::cmd_template_function_summaries(ctx, req).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_template_function_config<R: Runtime>(ctx: ClientCtx<R>, req: CmdTemplateFunctionConfigReq) -> Result<GetTemplateFunctionConfigResponse> {
|
async fn cmd_template_function_config<R: Runtime>(
|
||||||
|
ctx: ClientCtx<R>,
|
||||||
|
req: CmdTemplateFunctionConfigReq,
|
||||||
|
) -> Result<GetTemplateFunctionConfigResponse> {
|
||||||
Ok(yaak_commands::templates::cmd_template_function_config(ctx, req).await?)
|
Ok(yaak_commands::templates::cmd_template_function_config(ctx, req).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_get_http_authentication_summaries<R: Runtime>(ctx: ClientCtx<R>, req: CmdGetHttpAuthenticationSummariesReq) -> Result<Vec<GetHttpAuthenticationSummaryResponse>> {
|
async fn cmd_get_http_authentication_summaries<R: Runtime>(
|
||||||
|
ctx: ClientCtx<R>,
|
||||||
|
req: CmdGetHttpAuthenticationSummariesReq,
|
||||||
|
) -> Result<Vec<GetHttpAuthenticationSummaryResponse>> {
|
||||||
Ok(yaak_commands::auth::cmd_get_http_authentication_summaries(ctx, req).await?)
|
Ok(yaak_commands::auth::cmd_get_http_authentication_summaries(ctx, req).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_get_http_authentication_config<R: Runtime>(ctx: ClientCtx<R>, req: CmdGetHttpAuthenticationConfigReq) -> Result<GetHttpAuthenticationConfigResponse> {
|
async fn cmd_get_http_authentication_config<R: Runtime>(
|
||||||
|
ctx: ClientCtx<R>,
|
||||||
|
req: CmdGetHttpAuthenticationConfigReq,
|
||||||
|
) -> Result<GetHttpAuthenticationConfigResponse> {
|
||||||
Ok(yaak_commands::auth::cmd_get_http_authentication_config(ctx, req).await?)
|
Ok(yaak_commands::auth::cmd_get_http_authentication_config(ctx, req).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_call_http_request_action<R: Runtime>(ctx: ClientCtx<R>, req: CmdCallHttpRequestActionReq) -> Result<()> {
|
async fn cmd_call_http_request_action<R: Runtime>(
|
||||||
|
ctx: ClientCtx<R>,
|
||||||
|
req: CmdCallHttpRequestActionReq,
|
||||||
|
) -> Result<()> {
|
||||||
Ok(yaak_commands::actions::cmd_call_http_request_action(ctx, req).await?)
|
Ok(yaak_commands::actions::cmd_call_http_request_action(ctx, req).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_call_grpc_request_action<R: Runtime>(ctx: ClientCtx<R>, req: CmdCallGrpcRequestActionReq) -> Result<()> {
|
async fn cmd_call_grpc_request_action<R: Runtime>(
|
||||||
|
ctx: ClientCtx<R>,
|
||||||
|
req: CmdCallGrpcRequestActionReq,
|
||||||
|
) -> Result<()> {
|
||||||
Ok(yaak_commands::actions::cmd_call_grpc_request_action(ctx, req).await?)
|
Ok(yaak_commands::actions::cmd_call_grpc_request_action(ctx, req).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_call_http_authentication_action<R: Runtime>(ctx: ClientCtx<R>, req: CmdCallHttpAuthenticationActionReq) -> Result<()> {
|
async fn cmd_call_http_authentication_action<R: Runtime>(
|
||||||
|
ctx: ClientCtx<R>,
|
||||||
|
req: CmdCallHttpAuthenticationActionReq,
|
||||||
|
) -> Result<()> {
|
||||||
Ok(yaak_commands::auth::cmd_call_http_authentication_action(ctx, req).await?)
|
Ok(yaak_commands::auth::cmd_call_http_authentication_action(ctx, req).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_curl_to_request<R: Runtime>(ctx: ClientCtx<R>, req: CmdCurlToRequestReq) -> Result<HttpRequest> {
|
async fn cmd_curl_to_request<R: Runtime>(
|
||||||
|
ctx: ClientCtx<R>,
|
||||||
|
req: CmdCurlToRequestReq,
|
||||||
|
) -> Result<HttpRequest> {
|
||||||
Ok(yaak_commands::actions::cmd_curl_to_request(ctx, req).await?)
|
Ok(yaak_commands::actions::cmd_curl_to_request(ctx, req).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -551,83 +671,159 @@ async fn cmd_export_data<R: Runtime>(ctx: ClientCtx<R>, req: CmdExportDataReq) -
|
|||||||
Ok(yaak_commands::data::cmd_export_data(ctx, req).await?)
|
Ok(yaak_commands::data::cmd_export_data(ctx, req).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_save_base64_to_binary<R: Runtime>(ctx: ClientCtx<R>, req: CmdSaveBase64ToBinaryReq) -> Result<()> {
|
async fn cmd_save_base64_to_binary<R: Runtime>(
|
||||||
Ok(crate::cmd_save_base64_to_binary(ctx.window.app_handle().clone(), &req.filepath, &req.data).await?)
|
ctx: ClientCtx<R>,
|
||||||
|
req: CmdSaveBase64ToBinaryReq,
|
||||||
|
) -> Result<()> {
|
||||||
|
Ok(crate::cmd_save_base64_to_binary(ctx.window.app_handle().clone(), &req.filepath, &req.data)
|
||||||
|
.await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_save_response<R: Runtime>(ctx: ClientCtx<R>, req: CmdSaveResponseReq) -> Result<()> {
|
async fn cmd_save_response<R: Runtime>(ctx: ClientCtx<R>, req: CmdSaveResponseReq) -> Result<()> {
|
||||||
Ok(yaak_commands::responses::cmd_save_response(ctx, req).await?)
|
Ok(yaak_commands::responses::cmd_save_response(ctx, req).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_send_http_request<R: Runtime>(ctx: ClientCtx<R>, req: CmdSendHttpRequestReq) -> Result<HttpResponse> {
|
async fn cmd_send_http_request<R: Runtime>(
|
||||||
Ok(crate::cmd_send_http_request(ctx.window.app_handle().clone(), ctx.window.clone(), req.environment_id.as_deref(), req.cookie_jar_id.as_deref(), req.request_id).await?)
|
ctx: ClientCtx<R>,
|
||||||
|
req: CmdSendHttpRequestReq,
|
||||||
|
) -> Result<HttpResponse> {
|
||||||
|
Ok(crate::cmd_send_http_request(
|
||||||
|
ctx.window.app_handle().clone(),
|
||||||
|
ctx.window.clone(),
|
||||||
|
req.environment_id.as_deref(),
|
||||||
|
req.cookie_jar_id.as_deref(),
|
||||||
|
req.request_id,
|
||||||
|
)
|
||||||
|
.await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_reload_plugins<R: Runtime>(ctx: ClientCtx<R>, req: CmdReloadPluginsReq) -> Result<Vec<(String, String)>> {
|
async fn cmd_reload_plugins<R: Runtime>(
|
||||||
|
ctx: ClientCtx<R>,
|
||||||
|
req: CmdReloadPluginsReq,
|
||||||
|
) -> Result<Vec<(String, String)>> {
|
||||||
Ok(yaak_commands::actions::cmd_reload_plugins(ctx, req).await?)
|
Ok(yaak_commands::actions::cmd_reload_plugins(ctx, req).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_plugin_info<R: Runtime>(ctx: ClientCtx<R>, req: CmdPluginInfoReq) -> Result<PluginMetadata> {
|
async fn cmd_plugin_info<R: Runtime>(
|
||||||
|
ctx: ClientCtx<R>,
|
||||||
|
req: CmdPluginInfoReq,
|
||||||
|
) -> Result<PluginMetadata> {
|
||||||
Ok(yaak_commands::plugins::cmd_plugin_info(ctx, req).await?)
|
Ok(yaak_commands::plugins::cmd_plugin_info(ctx, req).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_delete_all_grpc_connections<R: Runtime>(ctx: ClientCtx<R>, req: CmdDeleteAllGrpcConnectionsReq) -> Result<()> {
|
async fn cmd_delete_all_grpc_connections<R: Runtime>(
|
||||||
|
ctx: ClientCtx<R>,
|
||||||
|
req: CmdDeleteAllGrpcConnectionsReq,
|
||||||
|
) -> Result<()> {
|
||||||
Ok(yaak_commands::models::cmd_delete_all_grpc_connections(ctx, req).await?)
|
Ok(yaak_commands::models::cmd_delete_all_grpc_connections(ctx, req).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_delete_send_history<R: Runtime>(ctx: ClientCtx<R>, req: CmdDeleteSendHistoryReq) -> Result<()> {
|
async fn cmd_delete_send_history<R: Runtime>(
|
||||||
|
ctx: ClientCtx<R>,
|
||||||
|
req: CmdDeleteSendHistoryReq,
|
||||||
|
) -> Result<()> {
|
||||||
Ok(yaak_commands::models::cmd_delete_send_history(ctx, req).await?)
|
Ok(yaak_commands::models::cmd_delete_send_history(ctx, req).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_delete_all_http_responses<R: Runtime>(ctx: ClientCtx<R>, req: CmdDeleteAllHttpResponsesReq) -> Result<()> {
|
async fn cmd_delete_all_http_responses<R: Runtime>(
|
||||||
|
ctx: ClientCtx<R>,
|
||||||
|
req: CmdDeleteAllHttpResponsesReq,
|
||||||
|
) -> Result<()> {
|
||||||
Ok(yaak_commands::models::cmd_delete_all_http_responses(ctx, req).await?)
|
Ok(yaak_commands::models::cmd_delete_all_http_responses(ctx, req).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_get_workspace_meta<R: Runtime>(ctx: ClientCtx<R>, req: CmdGetWorkspaceMetaReq) -> Result<WorkspaceMeta> {
|
async fn cmd_get_workspace_meta<R: Runtime>(
|
||||||
|
ctx: ClientCtx<R>,
|
||||||
|
req: CmdGetWorkspaceMetaReq,
|
||||||
|
) -> Result<WorkspaceMeta> {
|
||||||
Ok(yaak_commands::models::cmd_get_workspace_meta(ctx, req).await?)
|
Ok(yaak_commands::models::cmd_get_workspace_meta(ctx, req).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_new_child_window<R: Runtime>(ctx: ClientCtx<R>, req: CmdNewChildWindowReq) -> Result<()> {
|
async fn cmd_new_child_window<R: Runtime>(
|
||||||
Ok(crate::cmd_new_child_window(ctx.window.clone(), &req.url, &req.label, &req.title, req.inner_size).await?)
|
ctx: ClientCtx<R>,
|
||||||
|
req: CmdNewChildWindowReq,
|
||||||
|
) -> Result<()> {
|
||||||
|
Ok(crate::cmd_new_child_window(
|
||||||
|
ctx.window.clone(),
|
||||||
|
&req.url,
|
||||||
|
&req.label,
|
||||||
|
&req.title,
|
||||||
|
req.inner_size,
|
||||||
|
)
|
||||||
|
.await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_new_main_window<R: Runtime>(ctx: ClientCtx<R>, req: CmdNewMainWindowReq) -> Result<()> {
|
async fn cmd_new_main_window<R: Runtime>(
|
||||||
|
ctx: ClientCtx<R>,
|
||||||
|
req: CmdNewMainWindowReq,
|
||||||
|
) -> Result<()> {
|
||||||
Ok(crate::cmd_new_main_window(ctx.window.app_handle().clone(), &req.url).await?)
|
Ok(crate::cmd_new_main_window(ctx.window.app_handle().clone(), &req.url).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_check_for_updates<R: Runtime>(ctx: ClientCtx<R>, _req: CmdCheckForUpdatesReq) -> Result<bool> {
|
async fn cmd_check_for_updates<R: Runtime>(
|
||||||
Ok(crate::cmd_check_for_updates(ctx.window.clone(), ctx.window.app_handle().state::<Mutex<YaakUpdater>>()).await?)
|
ctx: ClientCtx<R>,
|
||||||
|
_req: CmdCheckForUpdatesReq,
|
||||||
|
) -> Result<bool> {
|
||||||
|
Ok(crate::cmd_check_for_updates(
|
||||||
|
ctx.window.clone(),
|
||||||
|
ctx.window.app_handle().state::<Mutex<YaakUpdater>>(),
|
||||||
|
)
|
||||||
|
.await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_decrypt_template<R: Runtime>(ctx: ClientCtx<R>, req: CmdDecryptTemplateReq) -> Result<String> {
|
async fn cmd_decrypt_template<R: Runtime>(
|
||||||
|
ctx: ClientCtx<R>,
|
||||||
|
req: CmdDecryptTemplateReq,
|
||||||
|
) -> Result<String> {
|
||||||
Ok(yaak_commands::encryption::cmd_decrypt_template(ctx, req).await?)
|
Ok(yaak_commands::encryption::cmd_decrypt_template(ctx, req).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_secure_template<R: Runtime>(ctx: ClientCtx<R>, req: CmdSecureTemplateReq) -> Result<String> {
|
async fn cmd_secure_template<R: Runtime>(
|
||||||
|
ctx: ClientCtx<R>,
|
||||||
|
req: CmdSecureTemplateReq,
|
||||||
|
) -> Result<String> {
|
||||||
Ok(yaak_commands::encryption::cmd_secure_template(ctx, req).await?)
|
Ok(yaak_commands::encryption::cmd_secure_template(ctx, req).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_get_themes<R: Runtime>(ctx: ClientCtx<R>, req: CmdGetThemesReq) -> Result<Vec<GetThemesResponse>> {
|
async fn cmd_get_themes<R: Runtime>(
|
||||||
|
ctx: ClientCtx<R>,
|
||||||
|
req: CmdGetThemesReq,
|
||||||
|
) -> Result<Vec<GetThemesResponse>> {
|
||||||
Ok(yaak_commands::templates::cmd_get_themes(ctx, req).await?)
|
Ok(yaak_commands::templates::cmd_get_themes(ctx, req).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_enable_encryption<R: Runtime>(ctx: ClientCtx<R>, req: CmdEnableEncryptionReq) -> Result<()> {
|
async fn cmd_enable_encryption<R: Runtime>(
|
||||||
|
ctx: ClientCtx<R>,
|
||||||
|
req: CmdEnableEncryptionReq,
|
||||||
|
) -> Result<()> {
|
||||||
Ok(yaak_commands::encryption::cmd_enable_encryption(ctx, req).await?)
|
Ok(yaak_commands::encryption::cmd_enable_encryption(ctx, req).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_reveal_workspace_key<R: Runtime>(ctx: ClientCtx<R>, req: CmdRevealWorkspaceKeyReq) -> Result<String> {
|
async fn cmd_reveal_workspace_key<R: Runtime>(
|
||||||
|
ctx: ClientCtx<R>,
|
||||||
|
req: CmdRevealWorkspaceKeyReq,
|
||||||
|
) -> Result<String> {
|
||||||
Ok(yaak_commands::encryption::cmd_reveal_workspace_key(ctx, req).await?)
|
Ok(yaak_commands::encryption::cmd_reveal_workspace_key(ctx, req).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_set_workspace_key<R: Runtime>(ctx: ClientCtx<R>, req: CmdSetWorkspaceKeyReq) -> Result<()> {
|
async fn cmd_set_workspace_key<R: Runtime>(
|
||||||
|
ctx: ClientCtx<R>,
|
||||||
|
req: CmdSetWorkspaceKeyReq,
|
||||||
|
) -> Result<()> {
|
||||||
Ok(yaak_commands::encryption::cmd_set_workspace_key(ctx, req).await?)
|
Ok(yaak_commands::encryption::cmd_set_workspace_key(ctx, req).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_disable_encryption<R: Runtime>(ctx: ClientCtx<R>, req: CmdDisableEncryptionReq) -> Result<()> {
|
async fn cmd_disable_encryption<R: Runtime>(
|
||||||
|
ctx: ClientCtx<R>,
|
||||||
|
req: CmdDisableEncryptionReq,
|
||||||
|
) -> Result<()> {
|
||||||
Ok(yaak_commands::encryption::cmd_disable_encryption(ctx, req).await?)
|
Ok(yaak_commands::encryption::cmd_disable_encryption(ctx, req).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_default_headers<R: Runtime>(ctx: ClientCtx<R>, req: CmdDefaultHeadersReq) -> Result<Vec<HttpRequestHeader>> {
|
async fn cmd_default_headers<R: Runtime>(
|
||||||
|
ctx: ClientCtx<R>,
|
||||||
|
req: CmdDefaultHeadersReq,
|
||||||
|
) -> Result<Vec<HttpRequestHeader>> {
|
||||||
Ok(yaak_commands::models::cmd_default_headers(ctx, req).await?)
|
Ok(yaak_commands::models::cmd_default_headers(ctx, req).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -649,27 +845,45 @@ async fn models_delete<R: Runtime>(ctx: ClientCtx<R>, req: ModelsDeleteReq) -> R
|
|||||||
Ok(deleted?)
|
Ok(deleted?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn models_duplicate<R: Runtime>(ctx: ClientCtx<R>, req: ModelsDuplicateReq) -> Result<String> {
|
async fn models_duplicate<R: Runtime>(
|
||||||
|
ctx: ClientCtx<R>,
|
||||||
|
req: ModelsDuplicateReq,
|
||||||
|
) -> Result<String> {
|
||||||
Ok(yaak_commands::models::models_duplicate(ctx, req).await?)
|
Ok(yaak_commands::models::models_duplicate(ctx, req).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn models_websocket_events<R: Runtime>(ctx: ClientCtx<R>, req: ModelsWebsocketEventsReq) -> Result<Vec<WebsocketEvent>> {
|
async fn models_websocket_events<R: Runtime>(
|
||||||
|
ctx: ClientCtx<R>,
|
||||||
|
req: ModelsWebsocketEventsReq,
|
||||||
|
) -> Result<Vec<WebsocketEvent>> {
|
||||||
Ok(yaak_commands::models::models_websocket_events(ctx, req).await?)
|
Ok(yaak_commands::models::models_websocket_events(ctx, req).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn models_grpc_events<R: Runtime>(ctx: ClientCtx<R>, req: ModelsGrpcEventsReq) -> Result<Vec<GrpcEvent>> {
|
async fn models_grpc_events<R: Runtime>(
|
||||||
|
ctx: ClientCtx<R>,
|
||||||
|
req: ModelsGrpcEventsReq,
|
||||||
|
) -> Result<Vec<GrpcEvent>> {
|
||||||
Ok(yaak_commands::models::models_grpc_events(ctx, req).await?)
|
Ok(yaak_commands::models::models_grpc_events(ctx, req).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn models_get_settings<R: Runtime>(ctx: ClientCtx<R>, req: ModelsGetSettingsReq) -> Result<Settings> {
|
async fn models_get_settings<R: Runtime>(
|
||||||
|
ctx: ClientCtx<R>,
|
||||||
|
req: ModelsGetSettingsReq,
|
||||||
|
) -> Result<Settings> {
|
||||||
Ok(yaak_commands::models::models_get_settings(ctx, req).await?)
|
Ok(yaak_commands::models::models_get_settings(ctx, req).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn models_get_graphql_introspection<R: Runtime>(ctx: ClientCtx<R>, req: ModelsGetGraphqlIntrospectionReq) -> Result<Option<GraphQlIntrospection>> {
|
async fn models_get_graphql_introspection<R: Runtime>(
|
||||||
|
ctx: ClientCtx<R>,
|
||||||
|
req: ModelsGetGraphqlIntrospectionReq,
|
||||||
|
) -> Result<Option<GraphQlIntrospection>> {
|
||||||
Ok(yaak_commands::models::models_get_graphql_introspection(ctx, req).await?)
|
Ok(yaak_commands::models::models_get_graphql_introspection(ctx, req).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn models_upsert_graphql_introspection<R: Runtime>(ctx: ClientCtx<R>, req: ModelsUpsertGraphqlIntrospectionReq) -> Result<GraphQlIntrospection> {
|
async fn models_upsert_graphql_introspection<R: Runtime>(
|
||||||
|
ctx: ClientCtx<R>,
|
||||||
|
req: ModelsUpsertGraphqlIntrospectionReq,
|
||||||
|
) -> Result<GraphQlIntrospection> {
|
||||||
Ok(yaak_commands::models::models_upsert_graphql_introspection(ctx, req).await?)
|
Ok(yaak_commands::models::models_upsert_graphql_introspection(ctx, req).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -680,7 +894,10 @@ async fn models_upsert_graphql_introspection<R: Runtime>(ctx: ClientCtx<R>, req:
|
|||||||
/// freezes the app"). Escape sequences sidestep it. This is a quirk of the
|
/// freezes the app"). Escape sequences sidestep it. This is a quirk of the
|
||||||
/// webview transport, not of the data, so it lives in the adapter rather than
|
/// webview transport, not of the data, so it lives in the adapter rather than
|
||||||
/// the shared handler.
|
/// the shared handler.
|
||||||
async fn models_workspace_models<R: Runtime>(ctx: ClientCtx<R>, req: ModelsWorkspaceModelsReq) -> Result<String> {
|
async fn models_workspace_models<R: Runtime>(
|
||||||
|
ctx: ClientCtx<R>,
|
||||||
|
req: ModelsWorkspaceModelsReq,
|
||||||
|
) -> Result<String> {
|
||||||
let json = yaak_commands::models::models_workspace_models(ctx, req).await?;
|
let json = yaak_commands::models::models_workspace_models(ctx, req).await?;
|
||||||
Ok(escape_str_for_webview(&json))
|
Ok(escape_str_for_webview(&json))
|
||||||
}
|
}
|
||||||
@@ -706,7 +923,10 @@ fn escape_str_for_webview(input: &str) -> String {
|
|||||||
.collect()
|
.collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_git_checkout<R: Runtime>(_ctx: ClientCtx<R>, req: CmdGitCheckoutReq) -> Result<String> {
|
async fn cmd_git_checkout<R: Runtime>(
|
||||||
|
_ctx: ClientCtx<R>,
|
||||||
|
req: CmdGitCheckoutReq,
|
||||||
|
) -> Result<String> {
|
||||||
Ok(crate::git_ext::cmd_git_checkout(&req.dir, &req.branch, req.force).await?)
|
Ok(crate::git_ext::cmd_git_checkout(&req.dir, &req.branch, req.force).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -714,31 +934,52 @@ async fn cmd_git_branch<R: Runtime>(_ctx: ClientCtx<R>, req: CmdGitBranchReq) ->
|
|||||||
Ok(crate::git_ext::cmd_git_branch(&req.dir, &req.branch, req.base.as_deref()).await?)
|
Ok(crate::git_ext::cmd_git_branch(&req.dir, &req.branch, req.base.as_deref()).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_git_delete_branch<R: Runtime>(_ctx: ClientCtx<R>, req: CmdGitDeleteBranchReq) -> Result<BranchDeleteResult> {
|
async fn cmd_git_delete_branch<R: Runtime>(
|
||||||
|
_ctx: ClientCtx<R>,
|
||||||
|
req: CmdGitDeleteBranchReq,
|
||||||
|
) -> Result<BranchDeleteResult> {
|
||||||
Ok(crate::git_ext::cmd_git_delete_branch(&req.dir, &req.branch, req.force).await?)
|
Ok(crate::git_ext::cmd_git_delete_branch(&req.dir, &req.branch, req.force).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_git_delete_remote_branch<R: Runtime>(_ctx: ClientCtx<R>, req: CmdGitDeleteRemoteBranchReq) -> Result<()> {
|
async fn cmd_git_delete_remote_branch<R: Runtime>(
|
||||||
|
_ctx: ClientCtx<R>,
|
||||||
|
req: CmdGitDeleteRemoteBranchReq,
|
||||||
|
) -> Result<()> {
|
||||||
Ok(crate::git_ext::cmd_git_delete_remote_branch(&req.dir, &req.branch).await?)
|
Ok(crate::git_ext::cmd_git_delete_remote_branch(&req.dir, &req.branch).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_git_merge_branch<R: Runtime>(_ctx: ClientCtx<R>, req: CmdGitMergeBranchReq) -> Result<()> {
|
async fn cmd_git_merge_branch<R: Runtime>(
|
||||||
|
_ctx: ClientCtx<R>,
|
||||||
|
req: CmdGitMergeBranchReq,
|
||||||
|
) -> Result<()> {
|
||||||
Ok(crate::git_ext::cmd_git_merge_branch(&req.dir, &req.branch).await?)
|
Ok(crate::git_ext::cmd_git_merge_branch(&req.dir, &req.branch).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_git_rename_branch<R: Runtime>(_ctx: ClientCtx<R>, req: CmdGitRenameBranchReq) -> Result<()> {
|
async fn cmd_git_rename_branch<R: Runtime>(
|
||||||
|
_ctx: ClientCtx<R>,
|
||||||
|
req: CmdGitRenameBranchReq,
|
||||||
|
) -> Result<()> {
|
||||||
Ok(crate::git_ext::cmd_git_rename_branch(&req.dir, &req.old_name, &req.new_name).await?)
|
Ok(crate::git_ext::cmd_git_rename_branch(&req.dir, &req.old_name, &req.new_name).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_git_status<R: Runtime>(_ctx: ClientCtx<R>, req: CmdGitStatusReq) -> Result<GitStatusSummary> {
|
async fn cmd_git_status<R: Runtime>(
|
||||||
|
_ctx: ClientCtx<R>,
|
||||||
|
req: CmdGitStatusReq,
|
||||||
|
) -> Result<GitStatusSummary> {
|
||||||
Ok(crate::git_ext::cmd_git_status(&req.dir).await?)
|
Ok(crate::git_ext::cmd_git_status(&req.dir).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_git_branch_info<R: Runtime>(_ctx: ClientCtx<R>, req: CmdGitBranchInfoReq) -> Result<GitBranchInfo> {
|
async fn cmd_git_branch_info<R: Runtime>(
|
||||||
|
_ctx: ClientCtx<R>,
|
||||||
|
req: CmdGitBranchInfoReq,
|
||||||
|
) -> Result<GitBranchInfo> {
|
||||||
Ok(crate::git_ext::cmd_git_branch_info(&req.dir).await?)
|
Ok(crate::git_ext::cmd_git_branch_info(&req.dir).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_git_worktree_status<R: Runtime>(_ctx: ClientCtx<R>, req: CmdGitWorktreeStatusReq) -> Result<GitWorktreeStatus> {
|
async fn cmd_git_worktree_status<R: Runtime>(
|
||||||
|
_ctx: ClientCtx<R>,
|
||||||
|
req: CmdGitWorktreeStatusReq,
|
||||||
|
) -> Result<GitWorktreeStatus> {
|
||||||
Ok(crate::git_ext::cmd_git_worktree_status(&req.dir).await?)
|
Ok(crate::git_ext::cmd_git_worktree_status(&req.dir).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -746,15 +987,25 @@ async fn cmd_git_log<R: Runtime>(_ctx: ClientCtx<R>, req: CmdGitLogReq) -> Resul
|
|||||||
Ok(crate::git_ext::cmd_git_log(&req.dir).await?)
|
Ok(crate::git_ext::cmd_git_log(&req.dir).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_git_log_for_file<R: Runtime>(_ctx: ClientCtx<R>, req: CmdGitLogForFileReq) -> Result<Vec<GitCommit>> {
|
async fn cmd_git_log_for_file<R: Runtime>(
|
||||||
|
_ctx: ClientCtx<R>,
|
||||||
|
req: CmdGitLogForFileReq,
|
||||||
|
) -> Result<Vec<GitCommit>> {
|
||||||
Ok(crate::git_ext::cmd_git_log_for_file(&req.dir, req.rela_path).await?)
|
Ok(crate::git_ext::cmd_git_log_for_file(&req.dir, req.rela_path).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_git_file_diff_for_commit<R: Runtime>(_ctx: ClientCtx<R>, req: CmdGitFileDiffForCommitReq) -> Result<GitFileDiff> {
|
async fn cmd_git_file_diff_for_commit<R: Runtime>(
|
||||||
Ok(crate::git_ext::cmd_git_file_diff_for_commit(&req.dir, &req.commit_oid, req.rela_path).await?)
|
_ctx: ClientCtx<R>,
|
||||||
|
req: CmdGitFileDiffForCommitReq,
|
||||||
|
) -> Result<GitFileDiff> {
|
||||||
|
Ok(crate::git_ext::cmd_git_file_diff_for_commit(&req.dir, &req.commit_oid, req.rela_path)
|
||||||
|
.await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_git_initialize<R: Runtime>(_ctx: ClientCtx<R>, req: CmdGitInitializeReq) -> Result<()> {
|
async fn cmd_git_initialize<R: Runtime>(
|
||||||
|
_ctx: ClientCtx<R>,
|
||||||
|
req: CmdGitInitializeReq,
|
||||||
|
) -> Result<()> {
|
||||||
Ok(crate::git_ext::cmd_git_initialize(&req.dir).await?)
|
Ok(crate::git_ext::cmd_git_initialize(&req.dir).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -778,11 +1029,17 @@ async fn cmd_git_pull<R: Runtime>(_ctx: ClientCtx<R>, req: CmdGitPullReq) -> Res
|
|||||||
Ok(crate::git_ext::cmd_git_pull(&req.dir).await?)
|
Ok(crate::git_ext::cmd_git_pull(&req.dir).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_git_pull_force_reset<R: Runtime>(_ctx: ClientCtx<R>, req: CmdGitPullForceResetReq) -> Result<PullResult> {
|
async fn cmd_git_pull_force_reset<R: Runtime>(
|
||||||
|
_ctx: ClientCtx<R>,
|
||||||
|
req: CmdGitPullForceResetReq,
|
||||||
|
) -> Result<PullResult> {
|
||||||
Ok(crate::git_ext::cmd_git_pull_force_reset(&req.dir, &req.remote, &req.branch).await?)
|
Ok(crate::git_ext::cmd_git_pull_force_reset(&req.dir, &req.remote, &req.branch).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_git_pull_merge<R: Runtime>(_ctx: ClientCtx<R>, req: CmdGitPullMergeReq) -> Result<PullResult> {
|
async fn cmd_git_pull_merge<R: Runtime>(
|
||||||
|
_ctx: ClientCtx<R>,
|
||||||
|
req: CmdGitPullMergeReq,
|
||||||
|
) -> Result<PullResult> {
|
||||||
Ok(crate::git_ext::cmd_git_pull_merge(&req.dir, &req.remote, &req.branch).await?)
|
Ok(crate::git_ext::cmd_git_pull_merge(&req.dir, &req.remote, &req.branch).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -794,27 +1051,47 @@ async fn cmd_git_unstage<R: Runtime>(_ctx: ClientCtx<R>, req: CmdGitUnstageReq)
|
|||||||
Ok(crate::git_ext::cmd_git_unstage(&req.dir, req.rela_paths).await?)
|
Ok(crate::git_ext::cmd_git_unstage(&req.dir, req.rela_paths).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_git_reset_changes<R: Runtime>(_ctx: ClientCtx<R>, req: CmdGitResetChangesReq) -> Result<()> {
|
async fn cmd_git_reset_changes<R: Runtime>(
|
||||||
|
_ctx: ClientCtx<R>,
|
||||||
|
req: CmdGitResetChangesReq,
|
||||||
|
) -> Result<()> {
|
||||||
Ok(crate::git_ext::cmd_git_reset_changes(&req.dir).await?)
|
Ok(crate::git_ext::cmd_git_reset_changes(&req.dir).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_git_restore_files<R: Runtime>(_ctx: ClientCtx<R>, req: CmdGitRestoreFilesReq) -> Result<()> {
|
async fn cmd_git_restore_files<R: Runtime>(
|
||||||
|
_ctx: ClientCtx<R>,
|
||||||
|
req: CmdGitRestoreFilesReq,
|
||||||
|
) -> Result<()> {
|
||||||
Ok(crate::git_ext::cmd_git_restore_files(&req.dir, req.rela_paths).await?)
|
Ok(crate::git_ext::cmd_git_restore_files(&req.dir, req.rela_paths).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_git_restore_file_from_commit<R: Runtime>(_ctx: ClientCtx<R>, req: CmdGitRestoreFileFromCommitReq) -> Result<()> {
|
async fn cmd_git_restore_file_from_commit<R: Runtime>(
|
||||||
Ok(crate::git_ext::cmd_git_restore_file_from_commit(&req.dir, &req.commit_oid, req.rela_path).await?)
|
_ctx: ClientCtx<R>,
|
||||||
|
req: CmdGitRestoreFileFromCommitReq,
|
||||||
|
) -> Result<()> {
|
||||||
|
Ok(crate::git_ext::cmd_git_restore_file_from_commit(&req.dir, &req.commit_oid, req.rela_path)
|
||||||
|
.await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_git_add_credential<R: Runtime>(_ctx: ClientCtx<R>, req: CmdGitAddCredentialReq) -> Result<()> {
|
async fn cmd_git_add_credential<R: Runtime>(
|
||||||
Ok(crate::git_ext::cmd_git_add_credential(&req.remote_url, &req.username, &req.password).await?)
|
_ctx: ClientCtx<R>,
|
||||||
|
req: CmdGitAddCredentialReq,
|
||||||
|
) -> Result<()> {
|
||||||
|
Ok(crate::git_ext::cmd_git_add_credential(&req.remote_url, &req.username, &req.password)
|
||||||
|
.await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_git_remotes<R: Runtime>(_ctx: ClientCtx<R>, req: CmdGitRemotesReq) -> Result<Vec<GitRemote>> {
|
async fn cmd_git_remotes<R: Runtime>(
|
||||||
|
_ctx: ClientCtx<R>,
|
||||||
|
req: CmdGitRemotesReq,
|
||||||
|
) -> Result<Vec<GitRemote>> {
|
||||||
Ok(crate::git_ext::cmd_git_remotes(&req.dir).await?)
|
Ok(crate::git_ext::cmd_git_remotes(&req.dir).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_git_add_remote<R: Runtime>(_ctx: ClientCtx<R>, req: CmdGitAddRemoteReq) -> Result<GitRemote> {
|
async fn cmd_git_add_remote<R: Runtime>(
|
||||||
|
_ctx: ClientCtx<R>,
|
||||||
|
req: CmdGitAddRemoteReq,
|
||||||
|
) -> Result<GitRemote> {
|
||||||
Ok(crate::git_ext::cmd_git_add_remote(&req.dir, &req.name, &req.url).await?)
|
Ok(crate::git_ext::cmd_git_add_remote(&req.dir, &req.name, &req.url).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -822,58 +1099,130 @@ async fn cmd_git_rm_remote<R: Runtime>(_ctx: ClientCtx<R>, req: CmdGitRmRemoteRe
|
|||||||
Ok(crate::git_ext::cmd_git_rm_remote(&req.dir, &req.name).await?)
|
Ok(crate::git_ext::cmd_git_rm_remote(&req.dir, &req.name).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_sync_calculate<R: Runtime>(ctx: ClientCtx<R>, req: CmdSyncCalculateReq) -> Result<Vec<SyncOp>> {
|
async fn cmd_sync_calculate<R: Runtime>(
|
||||||
Ok(crate::sync_ext::cmd_sync_calculate(ctx.window.app_handle().clone(), &req.workspace_id, &req.sync_dir).await?)
|
ctx: ClientCtx<R>,
|
||||||
|
req: CmdSyncCalculateReq,
|
||||||
|
) -> Result<Vec<SyncOp>> {
|
||||||
|
Ok(crate::sync_ext::cmd_sync_calculate(
|
||||||
|
ctx.window.app_handle().clone(),
|
||||||
|
&req.workspace_id,
|
||||||
|
&req.sync_dir,
|
||||||
|
)
|
||||||
|
.await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_sync_calculate_fs<R: Runtime>(_ctx: ClientCtx<R>, req: CmdSyncCalculateFsReq) -> Result<Vec<SyncOp>> {
|
async fn cmd_sync_calculate_fs<R: Runtime>(
|
||||||
|
_ctx: ClientCtx<R>,
|
||||||
|
req: CmdSyncCalculateFsReq,
|
||||||
|
) -> Result<Vec<SyncOp>> {
|
||||||
Ok(crate::sync_ext::cmd_sync_calculate_fs(&req.dir).await?)
|
Ok(crate::sync_ext::cmd_sync_calculate_fs(&req.dir).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_sync_apply<R: Runtime>(ctx: ClientCtx<R>, req: CmdSyncApplyReq) -> Result<()> {
|
async fn cmd_sync_apply<R: Runtime>(ctx: ClientCtx<R>, req: CmdSyncApplyReq) -> Result<()> {
|
||||||
Ok(crate::sync_ext::cmd_sync_apply(ctx.window.app_handle().clone(), req.sync_ops, &req.sync_dir, &req.workspace_id).await?)
|
Ok(crate::sync_ext::cmd_sync_apply(
|
||||||
|
ctx.window.app_handle().clone(),
|
||||||
|
req.sync_ops,
|
||||||
|
&req.sync_dir,
|
||||||
|
&req.workspace_id,
|
||||||
|
)
|
||||||
|
.await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_ws_delete_connections<R: Runtime>(ctx: ClientCtx<R>, req: CmdWsDeleteConnectionsReq) -> Result<()> {
|
async fn cmd_ws_delete_connections<R: Runtime>(
|
||||||
|
ctx: ClientCtx<R>,
|
||||||
|
req: CmdWsDeleteConnectionsReq,
|
||||||
|
) -> Result<()> {
|
||||||
Ok(yaak_commands::models::cmd_ws_delete_connections(ctx, req).await?)
|
Ok(yaak_commands::models::cmd_ws_delete_connections(ctx, req).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_ws_send<R: Runtime>(ctx: ClientCtx<R>, req: CmdWsSendReq) -> Result<WebsocketConnection> {
|
async fn cmd_ws_send<R: Runtime>(
|
||||||
Ok(crate::ws_ext::cmd_ws_send(&req.connection_id, req.environment_id.as_deref(), ctx.window.app_handle().clone(), ctx.window.clone(), ctx.window.app_handle().state::<Mutex<WebsocketManager>>()).await?)
|
ctx: ClientCtx<R>,
|
||||||
|
req: CmdWsSendReq,
|
||||||
|
) -> Result<WebsocketConnection> {
|
||||||
|
Ok(crate::ws_ext::cmd_ws_send(
|
||||||
|
&req.connection_id,
|
||||||
|
req.environment_id.as_deref(),
|
||||||
|
ctx.window.app_handle().clone(),
|
||||||
|
ctx.window.clone(),
|
||||||
|
ctx.window.app_handle().state::<Mutex<WebsocketManager>>(),
|
||||||
|
)
|
||||||
|
.await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_ws_close<R: Runtime>(ctx: ClientCtx<R>, req: CmdWsCloseReq) -> Result<WebsocketConnection> {
|
async fn cmd_ws_close<R: Runtime>(
|
||||||
Ok(crate::ws_ext::cmd_ws_close(&req.connection_id, ctx.window.app_handle().clone(), ctx.window.clone(), ctx.window.app_handle().state::<Mutex<WebsocketManager>>()).await?)
|
ctx: ClientCtx<R>,
|
||||||
|
req: CmdWsCloseReq,
|
||||||
|
) -> Result<WebsocketConnection> {
|
||||||
|
Ok(crate::ws_ext::cmd_ws_close(
|
||||||
|
&req.connection_id,
|
||||||
|
ctx.window.app_handle().clone(),
|
||||||
|
ctx.window.clone(),
|
||||||
|
ctx.window.app_handle().state::<Mutex<WebsocketManager>>(),
|
||||||
|
)
|
||||||
|
.await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_ws_connect<R: Runtime>(ctx: ClientCtx<R>, req: CmdWsConnectReq) -> Result<WebsocketConnection> {
|
async fn cmd_ws_connect<R: Runtime>(
|
||||||
Ok(crate::ws_ext::cmd_ws_connect(&req.request_id, req.environment_id.as_deref(), req.cookie_jar_id.as_deref(), ctx.window.app_handle().clone(), ctx.window.clone(), ctx.window.app_handle().state::<Mutex<WebsocketManager>>()).await?)
|
ctx: ClientCtx<R>,
|
||||||
|
req: CmdWsConnectReq,
|
||||||
|
) -> Result<WebsocketConnection> {
|
||||||
|
Ok(crate::ws_ext::cmd_ws_connect(
|
||||||
|
&req.request_id,
|
||||||
|
req.environment_id.as_deref(),
|
||||||
|
req.cookie_jar_id.as_deref(),
|
||||||
|
ctx.window.app_handle().clone(),
|
||||||
|
ctx.window.clone(),
|
||||||
|
ctx.window.app_handle().state::<Mutex<WebsocketManager>>(),
|
||||||
|
)
|
||||||
|
.await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_plugins_search<R: Runtime>(ctx: ClientCtx<R>, req: CmdPluginsSearchReq) -> Result<PluginSearchResponse> {
|
async fn cmd_plugins_search<R: Runtime>(
|
||||||
|
ctx: ClientCtx<R>,
|
||||||
|
req: CmdPluginsSearchReq,
|
||||||
|
) -> Result<PluginSearchResponse> {
|
||||||
Ok(crate::plugins_ext::cmd_plugins_search(ctx.window.app_handle().clone(), &req.query).await?)
|
Ok(crate::plugins_ext::cmd_plugins_search(ctx.window.app_handle().clone(), &req.query).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_plugins_install<R: Runtime>(ctx: ClientCtx<R>, req: CmdPluginsInstallReq) -> Result<()> {
|
async fn cmd_plugins_install<R: Runtime>(
|
||||||
|
ctx: ClientCtx<R>,
|
||||||
|
req: CmdPluginsInstallReq,
|
||||||
|
) -> Result<()> {
|
||||||
Ok(crate::plugins_ext::cmd_plugins_install(ctx.window.clone(), &req.name, req.version).await?)
|
Ok(crate::plugins_ext::cmd_plugins_install(ctx.window.clone(), &req.name, req.version).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_plugins_install_from_directory<R: Runtime>(ctx: ClientCtx<R>, req: CmdPluginsInstallFromDirectoryReq) -> Result<Plugin> {
|
async fn cmd_plugins_install_from_directory<R: Runtime>(
|
||||||
Ok(crate::plugins_ext::cmd_plugins_install_from_directory(ctx.window.clone(), &req.directory).await?)
|
ctx: ClientCtx<R>,
|
||||||
|
req: CmdPluginsInstallFromDirectoryReq,
|
||||||
|
) -> Result<Plugin> {
|
||||||
|
Ok(crate::plugins_ext::cmd_plugins_install_from_directory(ctx.window.clone(), &req.directory)
|
||||||
|
.await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_plugins_uninstall<R: Runtime>(ctx: ClientCtx<R>, req: CmdPluginsUninstallReq) -> Result<Plugin> {
|
async fn cmd_plugins_uninstall<R: Runtime>(
|
||||||
|
ctx: ClientCtx<R>,
|
||||||
|
req: CmdPluginsUninstallReq,
|
||||||
|
) -> Result<Plugin> {
|
||||||
Ok(crate::plugins_ext::cmd_plugins_uninstall(&req.plugin_id, ctx.window.clone()).await?)
|
Ok(crate::plugins_ext::cmd_plugins_uninstall(&req.plugin_id, ctx.window.clone()).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_plugin_init_errors<R: Runtime>(ctx: ClientCtx<R>, req: CmdPluginInitErrorsReq) -> Result<Vec<(String, String)>> {
|
async fn cmd_plugin_init_errors<R: Runtime>(
|
||||||
|
ctx: ClientCtx<R>,
|
||||||
|
req: CmdPluginInitErrorsReq,
|
||||||
|
) -> Result<Vec<(String, String)>> {
|
||||||
Ok(yaak_commands::plugins::cmd_plugin_init_errors(ctx, req).await?)
|
Ok(yaak_commands::plugins::cmd_plugin_init_errors(ctx, req).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_plugins_updates<R: Runtime>(ctx: ClientCtx<R>, _req: CmdPluginsUpdatesReq) -> Result<PluginUpdatesResponse> {
|
async fn cmd_plugins_updates<R: Runtime>(
|
||||||
|
ctx: ClientCtx<R>,
|
||||||
|
_req: CmdPluginsUpdatesReq,
|
||||||
|
) -> Result<PluginUpdatesResponse> {
|
||||||
Ok(crate::plugins_ext::cmd_plugins_updates(ctx.window.app_handle().clone()).await?)
|
Ok(crate::plugins_ext::cmd_plugins_updates(ctx.window.app_handle().clone()).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cmd_plugins_update_all<R: Runtime>(ctx: ClientCtx<R>, _req: CmdPluginsUpdateAllReq) -> Result<Vec<PluginNameVersion>> {
|
async fn cmd_plugins_update_all<R: Runtime>(
|
||||||
|
ctx: ClientCtx<R>,
|
||||||
|
_req: CmdPluginsUpdateAllReq,
|
||||||
|
) -> Result<Vec<PluginNameVersion>> {
|
||||||
Ok(crate::plugins_ext::cmd_plugins_update_all(ctx.window.clone()).await?)
|
Ok(crate::plugins_ext::cmd_plugins_update_all(ctx.window.clone()).await?)
|
||||||
}
|
}
|
||||||
@@ -12,8 +12,8 @@ use tokio::sync::watch;
|
|||||||
use yaak_rpc_schema::WatchResult;
|
use yaak_rpc_schema::WatchResult;
|
||||||
use yaak_sync::error::Error::InvalidSyncDirectory;
|
use yaak_sync::error::Error::InvalidSyncDirectory;
|
||||||
use yaak_sync::sync::{
|
use yaak_sync::sync::{
|
||||||
FsCandidate, SyncOp, apply_sync_ops, apply_sync_state_ops, compute_sync_ops, get_db_candidates,
|
FsCandidate, SyncOp, apply_db_sync_ops, apply_fs_sync_ops, apply_sync_state_ops,
|
||||||
get_fs_candidates,
|
compute_sync_ops, get_db_candidates, get_fs_candidates,
|
||||||
};
|
};
|
||||||
use yaak_sync::watch::{WatchEvent, watch_directory};
|
use yaak_sync::watch::{WatchEvent, watch_directory};
|
||||||
|
|
||||||
@@ -49,11 +49,14 @@ pub(crate) async fn cmd_sync_apply<R: Runtime>(
|
|||||||
sync_dir: &Path,
|
sync_dir: &Path,
|
||||||
workspace_id: &str,
|
workspace_id: &str,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
let db = app_handle.db();
|
// Files first, so the write transaction never waits on the filesystem
|
||||||
|
let pending = apply_fs_sync_ops(workspace_id, sync_dir, sync_ops)?;
|
||||||
let blobs = app_handle.blob_manager();
|
let blobs = app_handle.blob_manager();
|
||||||
let sync_state_ops = apply_sync_ops(&db, &blobs, workspace_id, sync_dir, sync_ops)?;
|
app_handle.db_manager().with_tx(|tx| {
|
||||||
apply_sync_state_ops(&db, workspace_id, sync_dir, sync_state_ops)?;
|
let sync_state_ops = apply_db_sync_ops(tx, &blobs, workspace_id, sync_dir, pending)?;
|
||||||
Ok(())
|
apply_sync_state_ops(tx, workspace_id, sync_dir, sync_state_ops)?;
|
||||||
|
Ok(())
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) async fn sync_watch<R, F>(
|
pub(crate) async fn sync_watch<R, F>(
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ use tauri::{AppHandle, Manager, Runtime, State, WebviewWindow};
|
|||||||
use tokio::sync::{Mutex, mpsc};
|
use tokio::sync::{Mutex, mpsc};
|
||||||
use tokio_tungstenite::tungstenite::Message;
|
use tokio_tungstenite::tungstenite::Message;
|
||||||
use url::Url;
|
use url::Url;
|
||||||
|
use yaak_commands::resolve::resolve_websocket_request;
|
||||||
use yaak_crypto::manager::EncryptionManager;
|
use yaak_crypto::manager::EncryptionManager;
|
||||||
use yaak_http::cookies::CookieStore;
|
use yaak_http::cookies::CookieStore;
|
||||||
use yaak_http::path_placeholders::apply_path_placeholders;
|
use yaak_http::path_placeholders::apply_path_placeholders;
|
||||||
@@ -26,7 +27,6 @@ use yaak_plugins::template_callback::PluginTemplateCallback;
|
|||||||
use yaak_templates::strip_json_comments::maybe_strip_json_comments;
|
use yaak_templates::strip_json_comments::maybe_strip_json_comments;
|
||||||
use yaak_templates::{RenderErrorBehavior, RenderOptions};
|
use yaak_templates::{RenderErrorBehavior, RenderOptions};
|
||||||
use yaak_tls::find_client_certificate;
|
use yaak_tls::find_client_certificate;
|
||||||
use yaak_commands::resolve::resolve_websocket_request;
|
|
||||||
use yaak_ws::{WebsocketManager, render_websocket_request};
|
use yaak_ws::{WebsocketManager, render_websocket_request};
|
||||||
|
|
||||||
pub async fn cmd_ws_send<R: Runtime>(
|
pub async fn cmd_ws_send<R: Runtime>(
|
||||||
@@ -43,18 +43,20 @@ pub async fn cmd_ws_send<R: Runtime>(
|
|||||||
{
|
{
|
||||||
Ok(connection) => Ok(connection),
|
Ok(connection) => Ok(connection),
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
app_handle.db().upsert_websocket_event(
|
app_handle.with_tx(|tx| {
|
||||||
&WebsocketEvent {
|
tx.upsert_websocket_event(
|
||||||
connection_id: connection.id.clone(),
|
&WebsocketEvent {
|
||||||
request_id: connection.request_id.clone(),
|
connection_id: connection.id.clone(),
|
||||||
workspace_id: connection.workspace_id.clone(),
|
request_id: connection.request_id.clone(),
|
||||||
is_server: false,
|
workspace_id: connection.workspace_id.clone(),
|
||||||
message_type: WebsocketEventType::Error,
|
is_server: false,
|
||||||
message: e.to_string().into(),
|
message_type: WebsocketEventType::Error,
|
||||||
..Default::default()
|
message: e.to_string().into(),
|
||||||
},
|
..Default::default()
|
||||||
&UpdateSource::from_window_label(window.label()),
|
},
|
||||||
)?;
|
&UpdateSource::from_window_label(window.label()),
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
|
||||||
Ok(connection)
|
Ok(connection)
|
||||||
}
|
}
|
||||||
@@ -96,18 +98,20 @@ async fn send_websocket_message<R: Runtime>(
|
|||||||
let mut ws_manager = ws_manager.lock().await;
|
let mut ws_manager = ws_manager.lock().await;
|
||||||
ws_manager.send(&connection.id, Message::Text(message.clone().into())).await?;
|
ws_manager.send(&connection.id, Message::Text(message.clone().into())).await?;
|
||||||
|
|
||||||
app_handle.db().upsert_websocket_event(
|
app_handle.with_tx(|tx| {
|
||||||
&WebsocketEvent {
|
tx.upsert_websocket_event(
|
||||||
connection_id: connection.id.clone(),
|
&WebsocketEvent {
|
||||||
request_id: request.id.clone(),
|
connection_id: connection.id.clone(),
|
||||||
workspace_id: connection.workspace_id.clone(),
|
request_id: request.id.clone(),
|
||||||
is_server: false,
|
workspace_id: connection.workspace_id.clone(),
|
||||||
message_type: WebsocketEventType::Text,
|
is_server: false,
|
||||||
message: message.into(),
|
message_type: WebsocketEventType::Text,
|
||||||
..Default::default()
|
message: message.into(),
|
||||||
},
|
..Default::default()
|
||||||
&UpdateSource::from_window_label(window.label()),
|
},
|
||||||
)?;
|
&UpdateSource::from_window_label(window.label()),
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
|
||||||
Ok(connection.clone())
|
Ok(connection.clone())
|
||||||
}
|
}
|
||||||
@@ -118,14 +122,13 @@ pub async fn cmd_ws_close<R: Runtime>(
|
|||||||
window: WebviewWindow<R>,
|
window: WebviewWindow<R>,
|
||||||
ws_manager: State<'_, Mutex<WebsocketManager>>,
|
ws_manager: State<'_, Mutex<WebsocketManager>>,
|
||||||
) -> Result<WebsocketConnection> {
|
) -> Result<WebsocketConnection> {
|
||||||
let connection = {
|
let connection = app_handle.with_tx(|tx| {
|
||||||
let db = app_handle.db();
|
let connection = tx.get_websocket_connection(connection_id)?;
|
||||||
let connection = db.get_websocket_connection(connection_id)?;
|
tx.upsert_websocket_connection(
|
||||||
db.upsert_websocket_connection(
|
|
||||||
&WebsocketConnection { state: WebsocketConnectionState::Closing, ..connection },
|
&WebsocketConnection { state: WebsocketConnectionState::Closing, ..connection },
|
||||||
&UpdateSource::from_window_label(window.label()),
|
&UpdateSource::from_window_label(window.label()),
|
||||||
)?
|
)
|
||||||
};
|
})?;
|
||||||
|
|
||||||
let mut ws_manager = ws_manager.lock().await;
|
let mut ws_manager = ws_manager.lock().await;
|
||||||
if let Err(e) = ws_manager.close(&connection.id).await {
|
if let Err(e) = ws_manager.close(&connection.id).await {
|
||||||
@@ -169,14 +172,16 @@ pub async fn cmd_ws_connect<R: Runtime>(
|
|||||||
)
|
)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
let connection = app_handle.db().upsert_websocket_connection(
|
let connection = app_handle.with_tx(|tx| {
|
||||||
&WebsocketConnection {
|
tx.upsert_websocket_connection(
|
||||||
workspace_id: request.workspace_id.clone(),
|
&WebsocketConnection {
|
||||||
request_id: request_id.to_string(),
|
workspace_id: request.workspace_id.clone(),
|
||||||
..Default::default()
|
request_id: request_id.to_string(),
|
||||||
},
|
..Default::default()
|
||||||
&UpdateSource::from_window_label(window.label()),
|
},
|
||||||
)?;
|
&UpdateSource::from_window_label(window.label()),
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
|
||||||
let (mut url, url_parameters) = apply_path_placeholders(&request.url, &request.url_parameters);
|
let (mut url, url_parameters) = apply_path_placeholders(&request.url, &request.url_parameters);
|
||||||
if !url.starts_with("ws://") && !url.starts_with("wss://") {
|
if !url.starts_with("ws://") && !url.starts_with("wss://") {
|
||||||
@@ -187,14 +192,16 @@ pub async fn cmd_ws_connect<R: Runtime>(
|
|||||||
let mut url = match Url::parse(&url) {
|
let mut url = match Url::parse(&url) {
|
||||||
Ok(url) => url,
|
Ok(url) => url,
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
return Ok(app_handle.db().upsert_websocket_connection(
|
return Ok(app_handle.with_tx(|tx| {
|
||||||
&WebsocketConnection {
|
tx.upsert_websocket_connection(
|
||||||
error: Some(format!("Failed to parse URL {}", e.to_string())),
|
&WebsocketConnection {
|
||||||
state: WebsocketConnectionState::Closed,
|
error: Some(format!("Failed to parse URL {}", e.to_string())),
|
||||||
..connection
|
state: WebsocketConnectionState::Closed,
|
||||||
},
|
..connection
|
||||||
&UpdateSource::from_window_label(window.label()),
|
},
|
||||||
)?);
|
&UpdateSource::from_window_label(window.label()),
|
||||||
|
)
|
||||||
|
})?);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -321,28 +328,32 @@ pub async fn cmd_ws_connect<R: Runtime>(
|
|||||||
{
|
{
|
||||||
Ok(r) => r,
|
Ok(r) => r,
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
return Ok(app_handle.db().upsert_websocket_connection(
|
return Ok(app_handle.with_tx(|tx| {
|
||||||
&WebsocketConnection {
|
tx.upsert_websocket_connection(
|
||||||
error: Some(e.to_string()),
|
&WebsocketConnection {
|
||||||
state: WebsocketConnectionState::Closed,
|
error: Some(e.to_string()),
|
||||||
..connection
|
state: WebsocketConnectionState::Closed,
|
||||||
},
|
..connection
|
||||||
&UpdateSource::from_window_label(window.label()),
|
},
|
||||||
)?);
|
&UpdateSource::from_window_label(window.label()),
|
||||||
|
)
|
||||||
|
})?);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
app_handle.db().upsert_websocket_event(
|
app_handle.with_tx(|tx| {
|
||||||
&WebsocketEvent {
|
tx.upsert_websocket_event(
|
||||||
connection_id: connection.id.clone(),
|
&WebsocketEvent {
|
||||||
request_id: request.id.clone(),
|
connection_id: connection.id.clone(),
|
||||||
workspace_id: connection.workspace_id.clone(),
|
request_id: request.id.clone(),
|
||||||
is_server: false,
|
workspace_id: connection.workspace_id.clone(),
|
||||||
message_type: WebsocketEventType::Open,
|
is_server: false,
|
||||||
..Default::default()
|
message_type: WebsocketEventType::Open,
|
||||||
},
|
..Default::default()
|
||||||
&UpdateSource::from_window_label(window.label()),
|
},
|
||||||
)?;
|
&UpdateSource::from_window_label(window.label()),
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
|
||||||
let response_headers = response
|
let response_headers = response
|
||||||
.headers()
|
.headers()
|
||||||
@@ -366,20 +377,22 @@ pub async fn cmd_ws_connect<R: Runtime>(
|
|||||||
if !set_cookie_headers.is_empty() {
|
if !set_cookie_headers.is_empty() {
|
||||||
store.store_cookies_from_response(&convert_ws_url_to_http(&url), &set_cookie_headers);
|
store.store_cookies_from_response(&convert_ws_url_to_http(&url), &set_cookie_headers);
|
||||||
cookie_jar.cookies = store.get_all_cookies();
|
cookie_jar.cookies = store.get_all_cookies();
|
||||||
app_handle.db().upsert_cookie_jar(cookie_jar, &UpdateSource::Background)?;
|
app_handle.with_tx(|tx| tx.upsert_cookie_jar(cookie_jar, &UpdateSource::Background))?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let connection = app_handle.db().upsert_websocket_connection(
|
let connection = app_handle.with_tx(|tx| {
|
||||||
&WebsocketConnection {
|
tx.upsert_websocket_connection(
|
||||||
state: WebsocketConnectionState::Connected,
|
&WebsocketConnection {
|
||||||
headers: response_headers,
|
state: WebsocketConnectionState::Connected,
|
||||||
status: response.status().as_u16() as i32,
|
headers: response_headers,
|
||||||
url: request.url.clone(),
|
status: response.status().as_u16() as i32,
|
||||||
..connection
|
url: request.url.clone(),
|
||||||
},
|
..connection
|
||||||
&UpdateSource::from_window_label(window.label()),
|
},
|
||||||
)?;
|
&UpdateSource::from_window_label(window.label()),
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
|
||||||
{
|
{
|
||||||
let connection_id = connection.id.clone();
|
let connection_id = connection.id.clone();
|
||||||
@@ -395,57 +408,60 @@ pub async fn cmd_ws_connect<R: Runtime>(
|
|||||||
}
|
}
|
||||||
|
|
||||||
app_handle
|
app_handle
|
||||||
.db()
|
.with_tx(|tx| {
|
||||||
.upsert_websocket_event(
|
tx.upsert_websocket_event(
|
||||||
&WebsocketEvent {
|
&WebsocketEvent {
|
||||||
connection_id: connection_id.clone(),
|
connection_id: connection_id.clone(),
|
||||||
request_id: request_id.clone(),
|
request_id: request_id.clone(),
|
||||||
workspace_id: workspace_id.clone(),
|
workspace_id: workspace_id.clone(),
|
||||||
is_server: true,
|
is_server: true,
|
||||||
message_type: match message {
|
message_type: match message {
|
||||||
Message::Text(_) => WebsocketEventType::Text,
|
Message::Text(_) => WebsocketEventType::Text,
|
||||||
Message::Binary(_) => WebsocketEventType::Binary,
|
Message::Binary(_) => WebsocketEventType::Binary,
|
||||||
Message::Ping(_) => WebsocketEventType::Ping,
|
Message::Ping(_) => WebsocketEventType::Ping,
|
||||||
Message::Pong(_) => WebsocketEventType::Pong,
|
Message::Pong(_) => WebsocketEventType::Pong,
|
||||||
Message::Close(_) => WebsocketEventType::Close,
|
Message::Close(_) => WebsocketEventType::Close,
|
||||||
// Raw frame will never happen during a read
|
// Raw frame will never happen during a read
|
||||||
Message::Frame(_) => WebsocketEventType::Frame,
|
Message::Frame(_) => WebsocketEventType::Frame,
|
||||||
|
},
|
||||||
|
message: message.into_data().into(),
|
||||||
|
..Default::default()
|
||||||
},
|
},
|
||||||
message: message.into_data().into(),
|
&UpdateSource::from_window_label(&window_label),
|
||||||
..Default::default()
|
)
|
||||||
},
|
})
|
||||||
&UpdateSource::from_window_label(&window_label),
|
|
||||||
)
|
|
||||||
.unwrap();
|
.unwrap();
|
||||||
}
|
}
|
||||||
info!("Websocket connection closed");
|
info!("Websocket connection closed");
|
||||||
if !has_written_close {
|
if !has_written_close {
|
||||||
app_handle
|
app_handle
|
||||||
.db()
|
.with_tx(|tx| {
|
||||||
.upsert_websocket_event(
|
tx.upsert_websocket_event(
|
||||||
&WebsocketEvent {
|
&WebsocketEvent {
|
||||||
connection_id: connection_id.clone(),
|
connection_id: connection_id.clone(),
|
||||||
request_id: request_id.clone(),
|
request_id: request_id.clone(),
|
||||||
workspace_id: workspace_id.clone(),
|
workspace_id: workspace_id.clone(),
|
||||||
is_server: true,
|
is_server: true,
|
||||||
message_type: WebsocketEventType::Close,
|
message_type: WebsocketEventType::Close,
|
||||||
..Default::default()
|
..Default::default()
|
||||||
},
|
},
|
||||||
&UpdateSource::from_window_label(&window_label),
|
&UpdateSource::from_window_label(&window_label),
|
||||||
)
|
)
|
||||||
|
})
|
||||||
.unwrap();
|
.unwrap();
|
||||||
}
|
}
|
||||||
app_handle
|
app_handle
|
||||||
.db()
|
.with_tx(|tx| {
|
||||||
.upsert_websocket_connection(
|
tx.upsert_websocket_connection(
|
||||||
&WebsocketConnection {
|
&WebsocketConnection {
|
||||||
workspace_id: request.workspace_id.clone(),
|
workspace_id: request.workspace_id.clone(),
|
||||||
request_id: request_id.to_string(),
|
request_id: request_id.to_string(),
|
||||||
state: WebsocketConnectionState::Closed,
|
state: WebsocketConnectionState::Closed,
|
||||||
..connection
|
..connection
|
||||||
},
|
},
|
||||||
&UpdateSource::from_window_label(&window_label),
|
&UpdateSource::from_window_label(&window_label),
|
||||||
)
|
)
|
||||||
|
})
|
||||||
.unwrap();
|
.unwrap();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -453,7 +469,6 @@ pub async fn cmd_ws_connect<R: Runtime>(
|
|||||||
Ok(connection)
|
Ok(connection)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/// Convert WS URL to HTTP URL for cookie filtering
|
/// Convert WS URL to HTTP URL for cookie filtering
|
||||||
/// WebSocket upgrade requests are HTTP requests initially, so HttpOnly cookies should apply
|
/// WebSocket upgrade requests are HTTP requests initially, so HttpOnly cookies should apply
|
||||||
fn convert_ws_url_to_http(ws_url: &Url) -> Url {
|
fn convert_ws_url_to_http(ws_url: &Url) -> Url {
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ use tauri::{AppHandle, Emitter, Manager, Runtime, WebviewWindow, is_dev};
|
|||||||
use ts_rs::TS;
|
use ts_rs::TS;
|
||||||
use yaak_api::{ApiClientKind, yaak_api_client};
|
use yaak_api::{ApiClientKind, yaak_api_client};
|
||||||
use yaak_common::platform::get_os_str;
|
use yaak_common::platform::get_os_str;
|
||||||
use yaak_models::client_db::ClientDb;
|
use yaak_models::client_db::{ClientDb, WriteDb};
|
||||||
use yaak_models::query_manager::QueryManager;
|
use yaak_models::query_manager::QueryManager;
|
||||||
use yaak_models::util::UpdateSource;
|
use yaak_models::util::UpdateSource;
|
||||||
|
|
||||||
@@ -17,6 +17,10 @@ use yaak_models::util::UpdateSource;
|
|||||||
/// This is needed temporarily until all crates are refactored to not use Tauri.
|
/// This is needed temporarily until all crates are refactored to not use Tauri.
|
||||||
trait QueryManagerExt<'a, R> {
|
trait QueryManagerExt<'a, R> {
|
||||||
fn db(&'a self) -> ClientDb<'a>;
|
fn db(&'a self) -> ClientDb<'a>;
|
||||||
|
fn with_tx<T>(
|
||||||
|
&'a self,
|
||||||
|
func: impl FnOnce(&WriteDb) -> yaak_models::error::Result<T>,
|
||||||
|
) -> yaak_models::error::Result<T>;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a, R: Runtime, M: Manager<R>> QueryManagerExt<'a, R> for M {
|
impl<'a, R: Runtime, M: Manager<R>> QueryManagerExt<'a, R> for M {
|
||||||
@@ -24,6 +28,14 @@ impl<'a, R: Runtime, M: Manager<R>> QueryManagerExt<'a, R> for M {
|
|||||||
let qm = self.state::<QueryManager>();
|
let qm = self.state::<QueryManager>();
|
||||||
qm.inner().connect()
|
qm.inner().connect()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn with_tx<T>(
|
||||||
|
&'a self,
|
||||||
|
func: impl FnOnce(&WriteDb) -> yaak_models::error::Result<T>,
|
||||||
|
) -> yaak_models::error::Result<T> {
|
||||||
|
let qm = self.state::<QueryManager>();
|
||||||
|
qm.inner().with_tx(func)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const KV_NAMESPACE: &str = "license";
|
const KV_NAMESPACE: &str = "license";
|
||||||
@@ -137,12 +149,17 @@ pub async fn activate_license<R: Runtime>(
|
|||||||
}
|
}
|
||||||
|
|
||||||
let body: ActivateLicenseResponsePayload = response.json().await?;
|
let body: ActivateLicenseResponsePayload = response.json().await?;
|
||||||
window.app_handle().db().set_key_value_str(
|
if let Err(e) = window.app_handle().with_tx(|tx| {
|
||||||
KV_ACTIVATION_ID_KEY,
|
tx.set_key_value_str(
|
||||||
KV_NAMESPACE,
|
KV_ACTIVATION_ID_KEY,
|
||||||
body.activation_id.as_str(),
|
KV_NAMESPACE,
|
||||||
&UpdateSource::from_window_label(window.label()),
|
body.activation_id.as_str(),
|
||||||
);
|
&UpdateSource::from_window_label(window.label()),
|
||||||
|
);
|
||||||
|
Ok(())
|
||||||
|
}) {
|
||||||
|
warn!("Failed to store license activation: {e}");
|
||||||
|
}
|
||||||
|
|
||||||
if let Err(e) = window.emit("license-activated", true) {
|
if let Err(e) = window.emit("license-activated", true) {
|
||||||
warn!("Failed to emit check-license event: {}", e);
|
warn!("Failed to emit check-license event: {}", e);
|
||||||
@@ -172,11 +189,13 @@ pub async fn deactivate_license<R: Runtime>(window: &WebviewWindow<R>) -> Result
|
|||||||
return Err(ServerError);
|
return Err(ServerError);
|
||||||
}
|
}
|
||||||
|
|
||||||
app_handle.db().delete_key_value(
|
app_handle.with_tx(|tx| {
|
||||||
KV_ACTIVATION_ID_KEY,
|
tx.delete_key_value(
|
||||||
KV_NAMESPACE,
|
KV_ACTIVATION_ID_KEY,
|
||||||
&UpdateSource::from_window_label(window.label()),
|
KV_NAMESPACE,
|
||||||
)?;
|
&UpdateSource::from_window_label(window.label()),
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
|
||||||
if let Err(e) = app_handle.emit("license-deactivated", true) {
|
if let Err(e) = app_handle.emit("license-deactivated", true) {
|
||||||
warn!("Failed to emit deactivate-license event: {}", e);
|
warn!("Failed to emit deactivate-license event: {}", e);
|
||||||
|
|||||||
@@ -21,7 +21,8 @@
|
|||||||
//! the second ask. Sharing the handle instead makes nested *reads* work the way
|
//! the second ask. Sharing the handle instead makes nested *reads* work the way
|
||||||
//! they do on the desktop; nested *write transactions* fail on both, only
|
//! they do on the desktop; nested *write transactions* fail on both, only
|
||||||
//! differently (here SQLite refuses the inner `BEGIN`; natively the inner
|
//! differently (here SQLite refuses the inner `BEGIN`; natively the inner
|
||||||
//! connection blocks on `busy_timeout` and then fails).
|
//! call waits for the one writer connection, which the outer call holds, and
|
||||||
|
//! times out).
|
||||||
|
|
||||||
#[cfg(not(target_arch = "wasm32"))]
|
#[cfg(not(target_arch = "wasm32"))]
|
||||||
mod imp {
|
mod imp {
|
||||||
|
|||||||
@@ -20,7 +20,9 @@ impl UpdateSource {
|
|||||||
#[derive(Debug, Clone, Serialize, Deserialize, TS)]
|
#[derive(Debug, Clone, Serialize, Deserialize, TS)]
|
||||||
#[serde(rename_all = "snake_case", tag = "type")]
|
#[serde(rename_all = "snake_case", tag = "type")]
|
||||||
pub enum ModelChangeEvent {
|
pub enum ModelChangeEvent {
|
||||||
Upsert { created: bool },
|
Upsert {
|
||||||
|
created: bool,
|
||||||
|
},
|
||||||
/// A delete for a workspace implies deletion of every model in that
|
/// A delete for a workspace implies deletion of every model in that
|
||||||
/// workspace — children are bulk-deleted without their own change rows or
|
/// workspace — children are bulk-deleted without their own change rows or
|
||||||
/// events, and consumers must prune the subtree themselves (the frontend
|
/// events, and consumers must prune the subtree themselves (the frontend
|
||||||
|
|||||||
@@ -331,17 +331,6 @@ export type ImportSource = {
|
|||||||
lastImportedAt: string;
|
lastImportedAt: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type ImportSourceResource = {
|
|
||||||
model: "import_source_resource";
|
|
||||||
createdAt: string;
|
|
||||||
updatedAt: string;
|
|
||||||
importSourceId: string;
|
|
||||||
sourceKey: string;
|
|
||||||
modelType: string;
|
|
||||||
modelId: string;
|
|
||||||
snapshot: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type InheritedBoolSetting = { enabled?: boolean; value: boolean };
|
export type InheritedBoolSetting = { enabled?: boolean; value: boolean };
|
||||||
|
|
||||||
export type InheritedHttpVersionSetting = { enabled?: boolean; value: HttpVersion };
|
export type InheritedHttpVersionSetting = { enabled?: boolean; value: HttpVersion };
|
||||||
|
|||||||
+81
-22
@@ -1,7 +1,21 @@
|
|||||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||||
import type { Environment, Folder, GrpcRequest, HttpRequest, WebsocketRequest, Workspace } from "./gen_models";
|
import type {
|
||||||
|
Environment,
|
||||||
|
Folder,
|
||||||
|
GrpcRequest,
|
||||||
|
HttpRequest,
|
||||||
|
WebsocketRequest,
|
||||||
|
Workspace,
|
||||||
|
} from "./gen_models";
|
||||||
|
|
||||||
export type BatchUpsertResult = { workspaces: Array<Workspace>, environments: Array<Environment>, folders: Array<Folder>, httpRequests: Array<HttpRequest>, grpcRequests: Array<GrpcRequest>, websocketRequests: Array<WebsocketRequest>, };
|
export type BatchUpsertResult = {
|
||||||
|
workspaces: Array<Workspace>;
|
||||||
|
environments: Array<Environment>;
|
||||||
|
folders: Array<Folder>;
|
||||||
|
httpRequests: Array<HttpRequest>;
|
||||||
|
grpcRequests: Array<GrpcRequest>;
|
||||||
|
websocketRequests: Array<WebsocketRequest>;
|
||||||
|
};
|
||||||
|
|
||||||
export type ImportConflictResolution = "keep_mine" | "take_source";
|
export type ImportConflictResolution = "keep_mine" | "take_source";
|
||||||
|
|
||||||
@@ -11,38 +25,83 @@ export type ImportConflictResolution = "keep_mine" | "take_source";
|
|||||||
* The destination workspace and optional folder IDs are captured in the plan so the preview describes
|
* The destination workspace and optional folder IDs are captured in the plan so the preview describes
|
||||||
* the exact destination that confirmation will use.
|
* the exact destination that confirmation will use.
|
||||||
*/
|
*/
|
||||||
export type ImportDestination = { "type": "new_workspace" } | { "type": "existing_workspace", workspaceId: string, folderId?: string, };
|
export type ImportDestination =
|
||||||
|
| { type: "new_workspace" }
|
||||||
|
| { type: "existing_workspace"; workspaceId: string; folderId?: string };
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Where an import's contents came from, used to link the committed workspace back to it.
|
* Where an import's contents came from, used to link the committed workspace back to it.
|
||||||
*/
|
*/
|
||||||
export type ImportOrigin = {
|
export type ImportOrigin = {
|
||||||
/**
|
/**
|
||||||
* The absolute file path or URL the contents were read from.
|
* The absolute file path or URL the contents were read from.
|
||||||
*/
|
*/
|
||||||
origin: string, label: string, };
|
origin: string;
|
||||||
|
label: string;
|
||||||
|
};
|
||||||
|
|
||||||
export type ImportPlan = { importer: string, destination: ImportDestination, resources: BatchUpsertResult, warnings: Array<ImportPlanWarning>,
|
export type ImportPlan = {
|
||||||
/**
|
importer: string;
|
||||||
* Stable source key for every model in `resources`, keyed by its planned ID.
|
destination: ImportDestination;
|
||||||
*/
|
resources: BatchUpsertResult;
|
||||||
sourceKeys: { [key in string]?: string },
|
warnings: Array<ImportPlanWarning>;
|
||||||
/**
|
/**
|
||||||
* One entry per plannable resource; commit applies only the selected ones.
|
* Stable source key for every model in `resources`, keyed by its planned ID.
|
||||||
*/
|
*/
|
||||||
items: Array<ImportPlanItem>, origin?: ImportOrigin, };
|
sourceKeys: { [key in string]?: string };
|
||||||
|
/**
|
||||||
|
* One entry per plannable resource; commit applies only the selected ones.
|
||||||
|
*/
|
||||||
|
items: Array<ImportPlanItem>;
|
||||||
|
origin?: ImportOrigin;
|
||||||
|
};
|
||||||
|
|
||||||
export type ImportPlanAction = "create" | "update" | "delete" | "unchanged" | "keep_local" | "conflict";
|
export type ImportPlanAction =
|
||||||
|
| "create"
|
||||||
|
| "update"
|
||||||
|
| "delete"
|
||||||
|
| "unchanged"
|
||||||
|
| "keep_local"
|
||||||
|
| "conflict"
|
||||||
|
| "ignored";
|
||||||
|
|
||||||
|
export type ImportPlanItem = {
|
||||||
|
action: ImportPlanAction;
|
||||||
|
model: ImportResourceType;
|
||||||
|
modelId: string;
|
||||||
|
name: string;
|
||||||
|
/**
|
||||||
|
* Planned parent folder ID for incoming resources; current parent for deletions.
|
||||||
|
*/
|
||||||
|
parentId?: string;
|
||||||
|
selected: boolean;
|
||||||
|
resolution?: ImportConflictResolution;
|
||||||
|
reason?: ImportPlanReason;
|
||||||
|
/**
|
||||||
|
* Fields where the source and the local copy disagree, so the preview can say why
|
||||||
|
*/
|
||||||
|
changedFields: Array<string>;
|
||||||
|
};
|
||||||
|
|
||||||
export type ImportPlanItem = { action: ImportPlanAction, model: ImportResourceType, modelId: string, name: string,
|
|
||||||
/**
|
/**
|
||||||
* Planned parent folder ID for incoming resources; current parent for deletions.
|
* Extra context for an action that would otherwise be indistinguishable from its plain form.
|
||||||
*/
|
*/
|
||||||
parentId?: string, selected: boolean, resolution?: ImportConflictResolution, };
|
export type ImportPlanReason = "moved_into_ignored_folder";
|
||||||
|
|
||||||
export type ImportPlanWarning = { title: string, detail: string, };
|
export type ImportPlanWarning = { title: string; detail: string; level: ImportPlanWarningLevel };
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether a plan's note is something to know or something to think twice about.
|
||||||
|
*/
|
||||||
|
export type ImportPlanWarningLevel = "info" | "warning";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The model types an import plan can contain.
|
* The model types an import plan can contain.
|
||||||
*/
|
*/
|
||||||
export type ImportResourceType = "environment" | "folder" | "grpc_request" | "http_request" | "websocket_request" | "workspace";
|
export type ImportResourceType =
|
||||||
|
| "environment"
|
||||||
|
| "folder"
|
||||||
|
| "grpc_request"
|
||||||
|
| "http_request"
|
||||||
|
| "websocket_request"
|
||||||
|
| "workspace";
|
||||||
@@ -29,11 +29,10 @@ use yaak_plugins::api::{PluginNameVersion, PluginSearchResponse, PluginUpdatesRe
|
|||||||
use yaak_plugins::events::{
|
use yaak_plugins::events::{
|
||||||
CallFolderActionRequest, CallGrpcRequestActionRequest, CallHttpRequestActionRequest,
|
CallFolderActionRequest, CallGrpcRequestActionRequest, CallHttpRequestActionRequest,
|
||||||
CallWebsocketRequestActionRequest, CallWorkspaceActionRequest, FilterResponse,
|
CallWebsocketRequestActionRequest, CallWorkspaceActionRequest, FilterResponse,
|
||||||
GetFolderActionsResponse, GetGrpcRequestActionsResponse,
|
GetFolderActionsResponse, GetGrpcRequestActionsResponse, GetHttpAuthenticationConfigResponse,
|
||||||
GetHttpAuthenticationConfigResponse, GetHttpAuthenticationSummaryResponse,
|
GetHttpAuthenticationSummaryResponse, GetHttpRequestActionsResponse,
|
||||||
GetHttpRequestActionsResponse, GetTemplateFunctionConfigResponse,
|
GetTemplateFunctionConfigResponse, GetTemplateFunctionSummaryResponse, GetThemesResponse,
|
||||||
GetTemplateFunctionSummaryResponse, GetThemesResponse, GetWebsocketRequestActionsResponse,
|
GetWebsocketRequestActionsResponse, GetWorkspaceActionsResponse, JsonPrimitive, RenderPurpose,
|
||||||
GetWorkspaceActionsResponse, JsonPrimitive, RenderPurpose,
|
|
||||||
};
|
};
|
||||||
use yaak_plugins::plugin_meta::PluginMetadata;
|
use yaak_plugins::plugin_meta::PluginMetadata;
|
||||||
use yaak_sse::sse::ServerSentEvent;
|
use yaak_sse::sse::ServerSentEvent;
|
||||||
|
|||||||
@@ -13,8 +13,9 @@ pub type BoxFuture<T> = Pin<Box<dyn Future<Output = T> + Send + 'static>>;
|
|||||||
/// `dispatch` call frame, so it cannot borrow, and contexts are cheap clones
|
/// `dispatch` call frame, so it cannot borrow, and contexts are cheap clones
|
||||||
/// (handles and `Arc`s). Synchronous handlers wrap into this via `rpc_handler!`
|
/// (handles and `Arc`s). Synchronous handlers wrap into this via `rpc_handler!`
|
||||||
/// with no visible change.
|
/// with no visible change.
|
||||||
type HandlerFn<Ctx> =
|
type HandlerFn<Ctx> = Box<
|
||||||
Box<dyn Fn(Ctx, serde_json::Value) -> BoxFuture<Result<serde_json::Value, RpcError>> + Send + Sync>;
|
dyn Fn(Ctx, serde_json::Value) -> BoxFuture<Result<serde_json::Value, RpcError>> + Send + Sync,
|
||||||
|
>;
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
pub struct RpcError {
|
pub struct RpcError {
|
||||||
@@ -249,9 +250,8 @@ macro_rules! rpc_handler_async {
|
|||||||
Box::new(|ctx, payload| {
|
Box::new(|ctx, payload| {
|
||||||
Box::pin(async move {
|
Box::pin(async move {
|
||||||
let req = serde_json::from_value(payload).map_err($crate::RpcError::from)?;
|
let req = serde_json::from_value(payload).map_err($crate::RpcError::from)?;
|
||||||
let res = $f(ctx, req)
|
let res =
|
||||||
.await
|
$f(ctx, req).await.map_err(|e| $crate::RpcError { message: e.to_string() })?;
|
||||||
.map_err(|e| $crate::RpcError { message: e.to_string() })?;
|
|
||||||
serde_json::to_value(res).map_err($crate::RpcError::from)
|
serde_json::to_value(res).map_err($crate::RpcError::from)
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -72,7 +72,7 @@ pub trait Host: Clone {
|
|||||||
self.query_manager().connect()
|
self.query_manager().connect()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn blobs(&self) -> BlobContext {
|
fn blobs(&self) -> BlobContext<'_> {
|
||||||
self.blob_manager().connect()
|
self.blob_manager().connect()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,10 +11,11 @@ use yaak_models::queries::workspaces::default_headers;
|
|||||||
use yaak_rpc_schema::*;
|
use yaak_rpc_schema::*;
|
||||||
|
|
||||||
pub async fn models_upsert<H: Host>(host: H, req: ModelsUpsertReq) -> Result<String> {
|
pub async fn models_upsert<H: Host>(host: H, req: ModelsUpsertReq) -> Result<String> {
|
||||||
let db = host.db();
|
|
||||||
let blobs = host.blob_manager();
|
let blobs = host.blob_manager();
|
||||||
let source = host.update_source();
|
let source = host.update_source();
|
||||||
Ok(yaak_models::models_ops::upsert_model(&db, blobs, req.model, &source)?)
|
Ok(host
|
||||||
|
.query_manager()
|
||||||
|
.with_tx(|tx| yaak_models::models_ops::upsert_model(tx, blobs, req.model, &source))?)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Deletes cascade — a workspace can hold thousands of requests — and run in a
|
/// Deletes cascade — a workspace can hold thousands of requests — and run in a
|
||||||
@@ -75,12 +76,9 @@ pub async fn models_upsert_graphql_introspection<H: Host>(
|
|||||||
req: ModelsUpsertGraphqlIntrospectionReq,
|
req: ModelsUpsertGraphqlIntrospectionReq,
|
||||||
) -> Result<GraphQlIntrospection> {
|
) -> Result<GraphQlIntrospection> {
|
||||||
let source = host.update_source();
|
let source = host.update_source();
|
||||||
Ok(host.db().upsert_graphql_introspection(
|
Ok(host.query_manager().with_tx(|tx| {
|
||||||
&req.workspace_id,
|
tx.upsert_graphql_introspection(&req.workspace_id, &req.request_id, req.content, &source)
|
||||||
&req.request_id,
|
})?)
|
||||||
req.content,
|
|
||||||
&source,
|
|
||||||
)?)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Everything the frontend's model store needs to boot, as one JSON string.
|
/// Everything the frontend's model store needs to boot, as one JSON string.
|
||||||
@@ -112,9 +110,16 @@ pub async fn models_workspace_models<H: PluginHost>(
|
|||||||
|
|
||||||
// Add the workspace children
|
// Add the workspace children
|
||||||
if let Some(wid) = req.workspace_id.as_deref() {
|
if let Some(wid) = req.workspace_id.as_deref() {
|
||||||
|
// Opening a workspace is where the rows it is assumed to have get created
|
||||||
|
host.query_manager().with_tx(|tx| {
|
||||||
|
tx.ensure_base_environment(wid)?;
|
||||||
|
tx.ensure_default_cookie_jar(wid)?;
|
||||||
|
tx.ensure_workspace_meta(wid)?;
|
||||||
|
Ok::<(), yaak_models::error::Error>(())
|
||||||
|
})?;
|
||||||
let db = host.db();
|
let db = host.db();
|
||||||
l.append(&mut db.list_cookie_jars(wid)?.into_iter().map(Into::into).collect());
|
l.append(&mut db.list_cookie_jars(wid)?.into_iter().map(Into::into).collect());
|
||||||
l.append(&mut db.list_environments_ensure_base(wid)?.into_iter().map(Into::into).collect());
|
l.append(&mut db.list_environments(wid)?.into_iter().map(Into::into).collect());
|
||||||
l.append(&mut db.list_folders(wid)?.into_iter().map(Into::into).collect());
|
l.append(&mut db.list_folders(wid)?.into_iter().map(Into::into).collect());
|
||||||
l.append(&mut db.list_grpc_connections(wid)?.into_iter().map(Into::into).collect());
|
l.append(&mut db.list_grpc_connections(wid)?.into_iter().map(Into::into).collect());
|
||||||
l.append(&mut db.list_grpc_requests(wid)?.into_iter().map(Into::into).collect());
|
l.append(&mut db.list_grpc_requests(wid)?.into_iter().map(Into::into).collect());
|
||||||
@@ -132,23 +137,26 @@ pub async fn cmd_get_workspace_meta<H: Host>(
|
|||||||
host: H,
|
host: H,
|
||||||
req: CmdGetWorkspaceMetaReq,
|
req: CmdGetWorkspaceMetaReq,
|
||||||
) -> Result<WorkspaceMeta> {
|
) -> Result<WorkspaceMeta> {
|
||||||
let db = host.db();
|
let workspace = host.db().get_workspace(&req.workspace_id)?;
|
||||||
let workspace = db.get_workspace(&req.workspace_id)?;
|
Ok(host.query_manager().with_tx(|tx| tx.ensure_workspace_meta(&workspace.id))?)
|
||||||
Ok(db.get_or_create_workspace_meta(&workspace.id)?)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn cmd_delete_all_grpc_connections<H: Host>(
|
pub async fn cmd_delete_all_grpc_connections<H: Host>(
|
||||||
host: H,
|
host: H,
|
||||||
req: CmdDeleteAllGrpcConnectionsReq,
|
req: CmdDeleteAllGrpcConnectionsReq,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
Ok(host.db().delete_all_grpc_connections_for_request(&req.request_id, &host.update_source())?)
|
Ok(host.query_manager().with_tx(|tx| {
|
||||||
|
tx.delete_all_grpc_connections_for_request(&req.request_id, &host.update_source())
|
||||||
|
})?)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn cmd_delete_all_http_responses<H: Host>(
|
pub async fn cmd_delete_all_http_responses<H: Host>(
|
||||||
host: H,
|
host: H,
|
||||||
req: CmdDeleteAllHttpResponsesReq,
|
req: CmdDeleteAllHttpResponsesReq,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
host.db().delete_all_http_responses_for_request(&req.request_id, &host.update_source())?;
|
host.query_manager().with_tx(|tx| {
|
||||||
|
tx.delete_all_http_responses_for_request(&req.request_id, &host.update_source())
|
||||||
|
})?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -156,9 +164,9 @@ pub async fn cmd_ws_delete_connections<H: Host>(
|
|||||||
host: H,
|
host: H,
|
||||||
req: CmdWsDeleteConnectionsReq,
|
req: CmdWsDeleteConnectionsReq,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
Ok(host
|
Ok(host.query_manager().with_tx(|tx| {
|
||||||
.db()
|
tx.delete_all_websocket_connections_for_request(&req.request_id, &host.update_source())
|
||||||
.delete_all_websocket_connections_for_request(&req.request_id, &host.update_source())?)
|
})?)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn cmd_delete_send_history<H: Host>(host: H, req: CmdDeleteSendHistoryReq) -> Result<()> {
|
pub async fn cmd_delete_send_history<H: Host>(host: H, req: CmdDeleteSendHistoryReq) -> Result<()> {
|
||||||
|
|||||||
@@ -118,6 +118,7 @@ impl Host for TestHost {
|
|||||||
#[tokio::test(flavor = "multi_thread")]
|
#[tokio::test(flavor = "multi_thread")]
|
||||||
async fn writes_carry_the_client_id() {
|
async fn writes_carry_the_client_id() {
|
||||||
let host = TestHost::new();
|
let host = TestHost::new();
|
||||||
|
host.drain_writes(); // the rows startup creates
|
||||||
|
|
||||||
let workspace = Workspace { name: "From a test".to_string(), ..Default::default() };
|
let workspace = Workspace { name: "From a test".to_string(), ..Default::default() };
|
||||||
let id = models_upsert(host.clone(), ModelsUpsertReq { model: AnyModel::Workspace(workspace) })
|
let id = models_upsert(host.clone(), ModelsUpsertReq { model: AnyModel::Workspace(workspace) })
|
||||||
@@ -406,21 +407,23 @@ async fn a_single_threaded_host_can_implement_the_trait() {
|
|||||||
// shared code; only the callback came from the host. Rendering a real
|
// shared code; only the callback came from the host. Rendering a real
|
||||||
// variable is what proves the chain was resolved rather than skipped.
|
// variable is what proves the chain was resolved rather than skipped.
|
||||||
let environment = host
|
let environment = host
|
||||||
.db()
|
.query_manager()
|
||||||
.upsert_environment(
|
.with_tx(|tx| {
|
||||||
&Environment {
|
tx.upsert_environment(
|
||||||
workspace_id: id.clone(),
|
&Environment {
|
||||||
name: "Test env".to_string(),
|
workspace_id: id.clone(),
|
||||||
variables: vec![EnvironmentVariable {
|
name: "Test env".to_string(),
|
||||||
enabled: true,
|
variables: vec![EnvironmentVariable {
|
||||||
name: "greeting".to_string(),
|
enabled: true,
|
||||||
value: "hello".to_string(),
|
name: "greeting".to_string(),
|
||||||
id: None,
|
value: "hello".to_string(),
|
||||||
}],
|
id: None,
|
||||||
..Default::default()
|
}],
|
||||||
},
|
..Default::default()
|
||||||
&host.update_source(),
|
},
|
||||||
)
|
&host.update_source(),
|
||||||
|
)
|
||||||
|
})
|
||||||
.expect("seed environment");
|
.expect("seed environment");
|
||||||
|
|
||||||
let rendered = cmd_render_template(
|
let rendered = cmd_render_template(
|
||||||
@@ -459,30 +462,33 @@ async fn auth_values_are_rendered_before_the_host_sees_them() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
let workspace = host
|
let workspace = host
|
||||||
.db()
|
.query_manager()
|
||||||
.upsert_workspace(
|
.with_tx(|tx| {
|
||||||
&Workspace { name: "Auth".to_string(), ..Default::default() },
|
tx.upsert_workspace(
|
||||||
&host.update_source(),
|
&Workspace { name: "Auth".to_string(), ..Default::default() },
|
||||||
)
|
&host.update_source(),
|
||||||
|
)
|
||||||
|
})
|
||||||
.expect("workspace");
|
.expect("workspace");
|
||||||
host.db()
|
host.query_manager()
|
||||||
.upsert_environment(
|
.with_tx(|tx| {
|
||||||
&Environment {
|
tx.upsert_environment(
|
||||||
workspace_id: workspace.id.clone(),
|
&Environment {
|
||||||
name: "Env".to_string(),
|
workspace_id: workspace.id.clone(),
|
||||||
variables: vec![EnvironmentVariable {
|
name: "Env".to_string(),
|
||||||
enabled: true,
|
variables: vec![EnvironmentVariable {
|
||||||
name: "token".to_string(),
|
enabled: true,
|
||||||
value: "s3cret".to_string(),
|
name: "token".to_string(),
|
||||||
id: None,
|
value: "s3cret".to_string(),
|
||||||
}],
|
id: None,
|
||||||
..Default::default()
|
}],
|
||||||
},
|
..Default::default()
|
||||||
&host.update_source(),
|
},
|
||||||
)
|
&host.update_source(),
|
||||||
|
)
|
||||||
|
})
|
||||||
.expect("environment");
|
.expect("environment");
|
||||||
let environment =
|
let environment = host.db().list_environments(&workspace.id).expect("list").remove(0);
|
||||||
host.db().list_environments_ensure_base(&workspace.id).expect("list").remove(0);
|
|
||||||
|
|
||||||
let mut values = HashMap::new();
|
let mut values = HashMap::new();
|
||||||
values.insert("password".to_string(), JsonPrimitive::String("${[ token ]}".to_string()));
|
values.insert("password".to_string(), JsonPrimitive::String("${[ token ]}".to_string()));
|
||||||
@@ -521,30 +527,33 @@ async fn template_function_values_are_rendered_before_the_host_sees_them() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
let workspace = host
|
let workspace = host
|
||||||
.db()
|
.query_manager()
|
||||||
.upsert_workspace(
|
.with_tx(|tx| {
|
||||||
&Workspace { name: "Functions".to_string(), ..Default::default() },
|
tx.upsert_workspace(
|
||||||
&host.update_source(),
|
&Workspace { name: "Functions".to_string(), ..Default::default() },
|
||||||
)
|
&host.update_source(),
|
||||||
|
)
|
||||||
|
})
|
||||||
.expect("workspace");
|
.expect("workspace");
|
||||||
host.db()
|
host.query_manager()
|
||||||
.upsert_environment(
|
.with_tx(|tx| {
|
||||||
&Environment {
|
tx.upsert_environment(
|
||||||
workspace_id: workspace.id.clone(),
|
&Environment {
|
||||||
name: "Env".to_string(),
|
workspace_id: workspace.id.clone(),
|
||||||
variables: vec![EnvironmentVariable {
|
name: "Env".to_string(),
|
||||||
enabled: true,
|
variables: vec![EnvironmentVariable {
|
||||||
name: "1PASSWORD_TOKEN".to_string(),
|
enabled: true,
|
||||||
value: "ops_abc123".to_string(),
|
name: "1PASSWORD_TOKEN".to_string(),
|
||||||
id: None,
|
value: "ops_abc123".to_string(),
|
||||||
}],
|
id: None,
|
||||||
..Default::default()
|
}],
|
||||||
},
|
..Default::default()
|
||||||
&host.update_source(),
|
},
|
||||||
)
|
&host.update_source(),
|
||||||
|
)
|
||||||
|
})
|
||||||
.expect("environment");
|
.expect("environment");
|
||||||
let environment =
|
let environment = host.db().list_environments(&workspace.id).expect("list").remove(0);
|
||||||
host.db().list_environments_ensure_base(&workspace.id).expect("list").remove(0);
|
|
||||||
|
|
||||||
let mut values = HashMap::new();
|
let mut values = HashMap::new();
|
||||||
values.insert("token".to_string(), JsonPrimitive::String("${[1PASSWORD_TOKEN]}".to_string()));
|
values.insert("token".to_string(), JsonPrimitive::String("${[1PASSWORD_TOKEN]}".to_string()));
|
||||||
|
|||||||
@@ -83,7 +83,7 @@ impl EncryptionManager {
|
|||||||
|
|
||||||
let workspace_meta = self.query_manager.with_tx::<WorkspaceMeta, Error>(|tx| {
|
let workspace_meta = self.query_manager.with_tx::<WorkspaceMeta, Error>(|tx| {
|
||||||
let workspace = tx.get_workspace(workspace_id)?;
|
let workspace = tx.get_workspace(workspace_id)?;
|
||||||
let workspace_meta = tx.get_or_create_workspace_meta(workspace_id)?;
|
let workspace_meta = tx.ensure_workspace_meta(workspace_id)?;
|
||||||
tx.upsert_workspace(
|
tx.upsert_workspace(
|
||||||
&Workspace { encryption_key_challenge, ..workspace },
|
&Workspace { encryption_key_challenge, ..workspace },
|
||||||
&UpdateSource::Background,
|
&UpdateSource::Background,
|
||||||
@@ -103,7 +103,7 @@ impl EncryptionManager {
|
|||||||
|
|
||||||
pub fn ensure_workspace_key(&self, workspace_id: &str) -> Result<WorkspaceMeta> {
|
pub fn ensure_workspace_key(&self, workspace_id: &str) -> Result<WorkspaceMeta> {
|
||||||
let workspace_meta =
|
let workspace_meta =
|
||||||
self.query_manager.connect().get_or_create_workspace_meta(workspace_id)?;
|
self.query_manager.with_tx(|tx| tx.ensure_workspace_meta(workspace_id))?;
|
||||||
|
|
||||||
// Already exists
|
// Already exists
|
||||||
if let Some(_) = workspace_meta.encryption_key {
|
if let Some(_) = workspace_meta.encryption_key {
|
||||||
@@ -120,7 +120,7 @@ impl EncryptionManager {
|
|||||||
|
|
||||||
self.query_manager.with_tx::<(), Error>(|tx| {
|
self.query_manager.with_tx::<(), Error>(|tx| {
|
||||||
let workspace = tx.get_workspace(workspace_id)?;
|
let workspace = tx.get_workspace(workspace_id)?;
|
||||||
let workspace_meta = tx.get_or_create_workspace_meta(workspace_id)?;
|
let workspace_meta = tx.ensure_workspace_meta(workspace_id)?;
|
||||||
|
|
||||||
// Clear encryption challenge on workspace
|
// Clear encryption challenge on workspace
|
||||||
tx.upsert_workspace(
|
tx.upsert_workspace(
|
||||||
@@ -152,10 +152,12 @@ impl EncryptionManager {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
let db = self.query_manager.connect();
|
let key = match self
|
||||||
let workspace_meta = db.get_or_create_workspace_meta(workspace_id)?;
|
.query_manager
|
||||||
|
.connect()
|
||||||
let key = match workspace_meta.encryption_key {
|
.get_workspace_meta(workspace_id)
|
||||||
|
.and_then(|m| m.encryption_key)
|
||||||
|
{
|
||||||
None => return Err(MissingWorkspaceKey),
|
None => return Err(MissingWorkspaceKey),
|
||||||
Some(k) => k,
|
Some(k) => k,
|
||||||
};
|
};
|
||||||
|
|||||||
Generated
+5
@@ -0,0 +1,5 @@
|
|||||||
|
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||||
|
|
||||||
|
export type MethodDefinition = { name: string, schema: string, clientStreaming: boolean, serverStreaming: boolean, };
|
||||||
|
|
||||||
|
export type ServiceDefinition = { name: string, methods: Array<MethodDefinition>, };
|
||||||
@@ -7,7 +7,7 @@
|
|||||||
use log::info;
|
use log::info;
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
use yaak_models::blob_manager::BlobManager;
|
use yaak_models::blob_manager::BlobManager;
|
||||||
use yaak_models::client_db::ClientDb;
|
use yaak_models::client_db::WriteDb;
|
||||||
use yaak_models::error::Result;
|
use yaak_models::error::Result;
|
||||||
|
|
||||||
const MODEL_CHANGES_RETENTION_HOURS: i64 = 1;
|
const MODEL_CHANGES_RETENTION_HOURS: i64 = 1;
|
||||||
@@ -44,7 +44,8 @@ impl Host {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Run once after the database is open, before the host answers anything.
|
/// Run once after the database is open, before the host answers anything.
|
||||||
pub fn on_launch(host: &Host, db: &ClientDb, blobs: &BlobManager) -> Result<()> {
|
/// Takes the write handle: a launch closes what the last session left open.
|
||||||
|
pub fn on_launch(host: &Host, db: &WriteDb, blobs: &BlobManager) -> Result<()> {
|
||||||
db.prune_model_changes_older_than_hours(MODEL_CHANGES_RETENTION_HOURS)?;
|
db.prune_model_changes_older_than_hours(MODEL_CHANGES_RETENTION_HOURS)?;
|
||||||
|
|
||||||
if host.role == Role::Owner {
|
if host.role == Role::Owner {
|
||||||
@@ -77,53 +78,48 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn only_the_owner_closes_what_the_last_session_left_open() {
|
fn only_the_owner_closes_what_the_last_session_left_open() {
|
||||||
let (query_manager, blob_manager, _rx) = init_in_memory().expect("Failed to init DB");
|
let (query_manager, blob_manager, _rx) = init_in_memory().expect("Failed to init DB");
|
||||||
let db = query_manager.connect();
|
|
||||||
let source = &UpdateSource::Background;
|
let source = &UpdateSource::Background;
|
||||||
|
|
||||||
let workspace = db
|
let pending = query_manager
|
||||||
.upsert_workspace(
|
.with_tx(|db| {
|
||||||
&Workspace { name: "Hooks".to_string(), ..Default::default() },
|
let workspace = db.upsert_workspace(
|
||||||
source,
|
&Workspace { name: "Hooks".to_string(), ..Default::default() },
|
||||||
)
|
source,
|
||||||
.unwrap();
|
)?;
|
||||||
let request = db
|
let request = db.upsert_http_request(
|
||||||
.upsert_http_request(
|
&HttpRequest { workspace_id: workspace.id.clone(), ..Default::default() },
|
||||||
&HttpRequest { workspace_id: workspace.id.clone(), ..Default::default() },
|
source,
|
||||||
source,
|
)?;
|
||||||
)
|
db.upsert_http_response(
|
||||||
.unwrap();
|
&HttpResponse {
|
||||||
let pending = db
|
request_id: request.id.clone(),
|
||||||
.upsert_http_response(
|
workspace_id: workspace.id.clone(),
|
||||||
&HttpResponse {
|
state: HttpResponseState::Connected,
|
||||||
request_id: request.id.clone(),
|
..Default::default()
|
||||||
workspace_id: workspace.id.clone(),
|
},
|
||||||
state: HttpResponseState::Connected,
|
source,
|
||||||
..Default::default()
|
&blob_manager,
|
||||||
},
|
)
|
||||||
source,
|
})
|
||||||
&blob_manager,
|
|
||||||
)
|
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
on_launch(&Host::guest(), &db, &blob_manager).unwrap();
|
query_manager.with_tx(|db| on_launch(&Host::guest(), db, &blob_manager)).unwrap();
|
||||||
let response = db.get_http_response(&pending.id).unwrap();
|
let response = query_manager.connect().get_http_response(&pending.id).unwrap();
|
||||||
assert!(matches!(response.state, HttpResponseState::Connected));
|
assert!(matches!(response.state, HttpResponseState::Connected));
|
||||||
|
|
||||||
on_launch(&Host::owner(), &db, &blob_manager).unwrap();
|
query_manager.with_tx(|db| on_launch(&Host::owner(), db, &blob_manager)).unwrap();
|
||||||
let response = db.get_http_response(&pending.id).unwrap();
|
let response = query_manager.connect().get_http_response(&pending.id).unwrap();
|
||||||
assert!(matches!(response.state, HttpResponseState::Closed));
|
assert!(matches!(response.state, HttpResponseState::Closed));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn owner_without_a_filesystem_still_sweeps_blobs() {
|
fn owner_without_a_filesystem_still_sweeps_blobs() {
|
||||||
let (query_manager, blob_manager, _rx) = init_in_memory().expect("Failed to init DB");
|
let (query_manager, blob_manager, _rx) = init_in_memory().expect("Failed to init DB");
|
||||||
let db = query_manager.connect();
|
blob_manager
|
||||||
{
|
.with_tx(|b| b.insert_chunk(&BodyChunk::new("rs_gone", 0, b"dead".to_vec())))
|
||||||
let blob_ctx = blob_manager.connect();
|
.unwrap();
|
||||||
blob_ctx.insert_chunk(&BodyChunk::new("rs_gone", 0, b"dead".to_vec())).unwrap();
|
|
||||||
}
|
|
||||||
|
|
||||||
on_launch(&Host::owner(), &db, &blob_manager).unwrap();
|
query_manager.with_tx(|db| on_launch(&Host::owner(), db, &blob_manager)).unwrap();
|
||||||
|
|
||||||
assert!(!blob_manager.connect().body_exists("rs_gone").unwrap());
|
assert!(!blob_manager.connect().body_exists("rs_gone").unwrap());
|
||||||
}
|
}
|
||||||
|
|||||||
+8
-2
@@ -356,8 +356,14 @@ export type ImportSourceResource = {
|
|||||||
importSourceId: string;
|
importSourceId: string;
|
||||||
sourceKey: string;
|
sourceKey: string;
|
||||||
modelType: string;
|
modelType: string;
|
||||||
modelId: string;
|
/**
|
||||||
snapshot: string;
|
* `None` once the user has decided not to import this key
|
||||||
|
*/
|
||||||
|
modelId?: string;
|
||||||
|
/**
|
||||||
|
* Hash of the resource as last applied or decided from the source, if one was recorded
|
||||||
|
*/
|
||||||
|
contentHash?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type InheritedBoolSetting = { enabled?: boolean; value: boolean };
|
export type InheritedBoolSetting = { enabled?: boolean; value: boolean };
|
||||||
|
|||||||
Generated
+81
-22
@@ -1,7 +1,21 @@
|
|||||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||||
import type { Environment, Folder, GrpcRequest, HttpRequest, WebsocketRequest, Workspace } from "./gen_models";
|
import type {
|
||||||
|
Environment,
|
||||||
|
Folder,
|
||||||
|
GrpcRequest,
|
||||||
|
HttpRequest,
|
||||||
|
WebsocketRequest,
|
||||||
|
Workspace,
|
||||||
|
} from "./gen_models";
|
||||||
|
|
||||||
export type BatchUpsertResult = { workspaces: Array<Workspace>, environments: Array<Environment>, folders: Array<Folder>, httpRequests: Array<HttpRequest>, grpcRequests: Array<GrpcRequest>, websocketRequests: Array<WebsocketRequest>, };
|
export type BatchUpsertResult = {
|
||||||
|
workspaces: Array<Workspace>;
|
||||||
|
environments: Array<Environment>;
|
||||||
|
folders: Array<Folder>;
|
||||||
|
httpRequests: Array<HttpRequest>;
|
||||||
|
grpcRequests: Array<GrpcRequest>;
|
||||||
|
websocketRequests: Array<WebsocketRequest>;
|
||||||
|
};
|
||||||
|
|
||||||
export type ImportConflictResolution = "keep_mine" | "take_source";
|
export type ImportConflictResolution = "keep_mine" | "take_source";
|
||||||
|
|
||||||
@@ -11,38 +25,83 @@ export type ImportConflictResolution = "keep_mine" | "take_source";
|
|||||||
* The destination workspace and optional folder IDs are captured in the plan so the preview describes
|
* The destination workspace and optional folder IDs are captured in the plan so the preview describes
|
||||||
* the exact destination that confirmation will use.
|
* the exact destination that confirmation will use.
|
||||||
*/
|
*/
|
||||||
export type ImportDestination = { "type": "new_workspace" } | { "type": "existing_workspace", workspaceId: string, folderId?: string, };
|
export type ImportDestination =
|
||||||
|
| { type: "new_workspace" }
|
||||||
|
| { type: "existing_workspace"; workspaceId: string; folderId?: string };
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Where an import's contents came from, used to link the committed workspace back to it.
|
* Where an import's contents came from, used to link the committed workspace back to it.
|
||||||
*/
|
*/
|
||||||
export type ImportOrigin = {
|
export type ImportOrigin = {
|
||||||
/**
|
/**
|
||||||
* The absolute file path or URL the contents were read from.
|
* The absolute file path or URL the contents were read from.
|
||||||
*/
|
*/
|
||||||
origin: string, label: string, };
|
origin: string;
|
||||||
|
label: string;
|
||||||
|
};
|
||||||
|
|
||||||
export type ImportPlan = { importer: string, destination: ImportDestination, resources: BatchUpsertResult, warnings: Array<ImportPlanWarning>,
|
export type ImportPlan = {
|
||||||
/**
|
importer: string;
|
||||||
* Stable source key for every model in `resources`, keyed by its planned ID.
|
destination: ImportDestination;
|
||||||
*/
|
resources: BatchUpsertResult;
|
||||||
sourceKeys: { [key in string]?: string },
|
warnings: Array<ImportPlanWarning>;
|
||||||
/**
|
/**
|
||||||
* One entry per plannable resource; commit applies only the selected ones.
|
* Stable source key for every model in `resources`, keyed by its planned ID.
|
||||||
*/
|
*/
|
||||||
items: Array<ImportPlanItem>, origin?: ImportOrigin, };
|
sourceKeys: { [key in string]?: string };
|
||||||
|
/**
|
||||||
|
* One entry per plannable resource; commit applies only the selected ones.
|
||||||
|
*/
|
||||||
|
items: Array<ImportPlanItem>;
|
||||||
|
origin?: ImportOrigin;
|
||||||
|
};
|
||||||
|
|
||||||
export type ImportPlanAction = "create" | "update" | "delete" | "unchanged" | "keep_local" | "conflict";
|
export type ImportPlanAction =
|
||||||
|
| "create"
|
||||||
|
| "update"
|
||||||
|
| "delete"
|
||||||
|
| "unchanged"
|
||||||
|
| "keep_local"
|
||||||
|
| "conflict"
|
||||||
|
| "ignored";
|
||||||
|
|
||||||
|
export type ImportPlanItem = {
|
||||||
|
action: ImportPlanAction;
|
||||||
|
model: ImportResourceType;
|
||||||
|
modelId: string;
|
||||||
|
name: string;
|
||||||
|
/**
|
||||||
|
* Planned parent folder ID for incoming resources; current parent for deletions.
|
||||||
|
*/
|
||||||
|
parentId?: string;
|
||||||
|
selected: boolean;
|
||||||
|
resolution?: ImportConflictResolution;
|
||||||
|
reason?: ImportPlanReason;
|
||||||
|
/**
|
||||||
|
* Fields where the source and the local copy disagree, so the preview can say why
|
||||||
|
*/
|
||||||
|
changedFields: Array<string>;
|
||||||
|
};
|
||||||
|
|
||||||
export type ImportPlanItem = { action: ImportPlanAction, model: ImportResourceType, modelId: string, name: string,
|
|
||||||
/**
|
/**
|
||||||
* Planned parent folder ID for incoming resources; current parent for deletions.
|
* Extra context for an action that would otherwise be indistinguishable from its plain form.
|
||||||
*/
|
*/
|
||||||
parentId?: string, selected: boolean, resolution?: ImportConflictResolution, };
|
export type ImportPlanReason = "moved_into_ignored_folder";
|
||||||
|
|
||||||
export type ImportPlanWarning = { title: string, detail: string, };
|
export type ImportPlanWarning = { title: string; detail: string; level: ImportPlanWarningLevel };
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether a plan's note is something to know or something to think twice about.
|
||||||
|
*/
|
||||||
|
export type ImportPlanWarningLevel = "info" | "warning";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The model types an import plan can contain.
|
* The model types an import plan can contain.
|
||||||
*/
|
*/
|
||||||
export type ImportResourceType = "environment" | "folder" | "grpc_request" | "http_request" | "websocket_request" | "workspace";
|
export type ImportResourceType =
|
||||||
|
| "environment"
|
||||||
|
| "folder"
|
||||||
|
| "grpc_request"
|
||||||
|
| "http_request"
|
||||||
|
| "websocket_request"
|
||||||
|
| "workspace";
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
-- Replace the per-resource snapshot with a content hash, and let a row exist without a model
|
||||||
|
-- so a resource the user chose not to import can be remembered.
|
||||||
|
CREATE TABLE import_source_resources_new
|
||||||
|
(
|
||||||
|
model TEXT DEFAULT 'import_source_resource' NOT NULL,
|
||||||
|
created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||||
|
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||||
|
import_source_id TEXT NOT NULL,
|
||||||
|
source_key TEXT NOT NULL,
|
||||||
|
model_type TEXT NOT NULL,
|
||||||
|
model_id TEXT,
|
||||||
|
content_hash TEXT,
|
||||||
|
PRIMARY KEY (import_source_id, source_key)
|
||||||
|
);
|
||||||
|
|
||||||
|
INSERT INTO import_source_resources_new (model, created_at, updated_at, import_source_id,
|
||||||
|
source_key, model_type, model_id, content_hash)
|
||||||
|
SELECT model, created_at, updated_at, import_source_id, source_key, model_type, model_id, NULL
|
||||||
|
FROM import_source_resources;
|
||||||
|
|
||||||
|
DROP TABLE import_source_resources;
|
||||||
|
|
||||||
|
ALTER TABLE import_source_resources_new
|
||||||
|
RENAME TO import_source_resources;
|
||||||
@@ -1,9 +1,11 @@
|
|||||||
|
use crate::error::Error::GenericError;
|
||||||
use crate::error::Result;
|
use crate::error::Result;
|
||||||
use crate::util::generate_prefixed_id;
|
use crate::util::generate_prefixed_id;
|
||||||
use include_dir::{Dir, include_dir};
|
use include_dir::{Dir, include_dir};
|
||||||
use log::{debug, info};
|
use log::{debug, info};
|
||||||
use rusqlite::{OptionalExtension, params};
|
use rusqlite::{OptionalExtension, Transaction, TransactionBehavior, params};
|
||||||
use yaak_database::{SqliteConn, SqlitePool};
|
use std::ops::Deref;
|
||||||
|
use yaak_database::{ConnectionOrTx, SqlitePool};
|
||||||
|
|
||||||
static BLOB_MIGRATIONS_DIR: Dir = include_dir!("$CARGO_MANIFEST_DIR/blob_migrations");
|
static BLOB_MIGRATIONS_DIR: Dir = include_dir!("$CARGO_MANIFEST_DIR/blob_migrations");
|
||||||
|
|
||||||
@@ -22,41 +24,64 @@ impl BodyChunk {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Manages the blob database connection pool.
|
/// Manages the blob database: a reader pool and a single writer, for the
|
||||||
// Pool is internally synchronized — don't wrap it in a Mutex. A Mutex held across the
|
/// same reason as [`crate::query_manager::QueryManager`].
|
||||||
|
// Pools are internally synchronized — don't wrap them in a Mutex. A Mutex held across the
|
||||||
// blocking `get()` serializes every blob access behind the slowest waiter, freezing the
|
// blocking `get()` serializes every blob access behind the slowest waiter, freezing the
|
||||||
// whole app whenever the pool is exhausted.
|
// whole app whenever the pool is exhausted.
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct BlobManager {
|
pub struct BlobManager {
|
||||||
pool: SqlitePool,
|
readers: SqlitePool,
|
||||||
|
writer: SqlitePool,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl BlobManager {
|
impl BlobManager {
|
||||||
pub fn new(pool: SqlitePool) -> Self {
|
/// `writer` must be a pool with a single connection.
|
||||||
Self { pool }
|
pub fn new(readers: SqlitePool, writer: SqlitePool) -> Self {
|
||||||
|
Self { readers, writer }
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn connect(&self) -> BlobContext {
|
/// A read handle from the reader pool.
|
||||||
let conn = self.pool.get().expect("Failed to get blob DB connection from pool");
|
pub fn connect(&self) -> BlobContext<'_> {
|
||||||
BlobContext { conn }
|
let conn = self.readers.get().expect("Failed to get blob DB connection from pool");
|
||||||
|
BlobContext { conn: ConnectionOrTx::Connection(conn) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Run `func` in a transaction on the writer connection.
|
||||||
|
pub fn with_tx<T, E>(
|
||||||
|
&self,
|
||||||
|
func: impl FnOnce(&BlobWriter) -> std::result::Result<T, E>,
|
||||||
|
) -> std::result::Result<T, E>
|
||||||
|
where
|
||||||
|
E: From<crate::error::Error>,
|
||||||
|
{
|
||||||
|
let conn = self.writer.get().map_err(crate::error::Error::SqlPoolError)?;
|
||||||
|
let tx = Transaction::new_unchecked(&conn, TransactionBehavior::Immediate)
|
||||||
|
.map_err(crate::error::Error::SqlError)?;
|
||||||
|
let writer = BlobWriter { ctx: BlobContext { conn: ConnectionOrTx::Transaction(&tx) } };
|
||||||
|
match func(&writer) {
|
||||||
|
Ok(val) => {
|
||||||
|
tx.commit().map_err(|e| {
|
||||||
|
GenericError(format!("Failed to commit blob transaction {e:?}"))
|
||||||
|
})?;
|
||||||
|
Ok(val)
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
tx.rollback().map_err(|e| {
|
||||||
|
GenericError(format!("Failed to rollback blob transaction {e:?}"))
|
||||||
|
})?;
|
||||||
|
Err(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Context for blob database operations.
|
/// Read handle for the blob database.
|
||||||
pub struct BlobContext {
|
pub struct BlobContext<'a> {
|
||||||
conn: SqliteConn,
|
conn: ConnectionOrTx<'a>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl BlobContext {
|
impl<'a> BlobContext<'a> {
|
||||||
/// Insert a single chunk.
|
|
||||||
pub fn insert_chunk(&self, chunk: &BodyChunk) -> Result<()> {
|
|
||||||
self.conn.execute(
|
|
||||||
"INSERT INTO body_chunks (id, body_id, chunk_index, data) VALUES (?1, ?2, ?3, ?4)",
|
|
||||||
params![chunk.id, chunk.body_id, chunk.chunk_index, chunk.data],
|
|
||||||
)?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Get all chunks for a body, ordered by chunk_index.
|
/// Get all chunks for a body, ordered by chunk_index.
|
||||||
pub fn get_chunks(&self, body_id: &str) -> Result<Vec<BodyChunk>> {
|
pub fn get_chunks(&self, body_id: &str) -> Result<Vec<BodyChunk>> {
|
||||||
let mut stmt = self.conn.prepare(
|
let mut stmt = self.conn.prepare(
|
||||||
@@ -87,25 +112,11 @@ impl BlobContext {
|
|||||||
Ok(ids)
|
Ok(ids)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Delete all chunks for a body.
|
/// Get total size of a body without loading data.
|
||||||
pub fn delete_chunks(&self, body_id: &str) -> Result<()> {
|
|
||||||
self.conn.execute("DELETE FROM body_chunks WHERE body_id = ?1", params![body_id])?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Delete all chunks matching a body_id prefix (e.g., "rs_abc123.%" to delete all bodies for a response).
|
|
||||||
pub fn delete_chunks_like(&self, body_id_prefix: &str) -> Result<()> {
|
|
||||||
self.conn
|
|
||||||
.execute("DELETE FROM body_chunks WHERE body_id LIKE ?1", params![body_id_prefix])?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Get total size of a body without loading data.
|
|
||||||
impl BlobContext {
|
|
||||||
pub fn get_body_size(&self, body_id: &str) -> Result<usize> {
|
pub fn get_body_size(&self, body_id: &str) -> Result<usize> {
|
||||||
let size: i64 = self
|
let size: i64 = self
|
||||||
.conn
|
.conn
|
||||||
|
.resolve()
|
||||||
.query_row(
|
.query_row(
|
||||||
"SELECT COALESCE(SUM(LENGTH(data)), 0) FROM body_chunks WHERE body_id = ?1",
|
"SELECT COALESCE(SUM(LENGTH(data)), 0) FROM body_chunks WHERE body_id = ?1",
|
||||||
params![body_id],
|
params![body_id],
|
||||||
@@ -119,6 +130,7 @@ impl BlobContext {
|
|||||||
pub fn body_exists(&self, body_id: &str) -> Result<bool> {
|
pub fn body_exists(&self, body_id: &str) -> Result<bool> {
|
||||||
let count: i64 = self
|
let count: i64 = self
|
||||||
.conn
|
.conn
|
||||||
|
.resolve()
|
||||||
.query_row(
|
.query_row(
|
||||||
"SELECT COUNT(*) FROM body_chunks WHERE body_id = ?1",
|
"SELECT COUNT(*) FROM body_chunks WHERE body_id = ?1",
|
||||||
params![body_id],
|
params![body_id],
|
||||||
@@ -129,6 +141,44 @@ impl BlobContext {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Write handle for the blob database. Derefs to [`BlobContext`] for reads.
|
||||||
|
pub struct BlobWriter<'a> {
|
||||||
|
ctx: BlobContext<'a>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> Deref for BlobWriter<'a> {
|
||||||
|
type Target = BlobContext<'a>;
|
||||||
|
|
||||||
|
fn deref(&self) -> &BlobContext<'a> {
|
||||||
|
&self.ctx
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> BlobWriter<'a> {
|
||||||
|
/// Insert a single chunk.
|
||||||
|
pub fn insert_chunk(&self, chunk: &BodyChunk) -> Result<()> {
|
||||||
|
self.conn.execute(
|
||||||
|
"INSERT INTO body_chunks (id, body_id, chunk_index, data) VALUES (?1, ?2, ?3, ?4)",
|
||||||
|
params![chunk.id, chunk.body_id, chunk.chunk_index, chunk.data],
|
||||||
|
)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Delete all chunks for a body.
|
||||||
|
pub fn delete_chunks(&self, body_id: &str) -> Result<()> {
|
||||||
|
self.conn.execute("DELETE FROM body_chunks WHERE body_id = ?1", params![body_id])?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Delete all chunks matching a body_id prefix (e.g., "rs_abc123.%" to delete all
|
||||||
|
/// bodies for a response).
|
||||||
|
pub fn delete_chunks_like(&self, body_id_prefix: &str) -> Result<()> {
|
||||||
|
self.conn
|
||||||
|
.execute("DELETE FROM body_chunks WHERE body_id LIKE ?1", params![body_id_prefix])?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Run migrations for the blob database.
|
/// Run migrations for the blob database.
|
||||||
pub fn migrate_blob_db(pool: &SqlitePool) -> Result<()> {
|
pub fn migrate_blob_db(pool: &SqlitePool) -> Result<()> {
|
||||||
info!("Running blob database migrations");
|
info!("Running blob database migrations");
|
||||||
@@ -196,28 +246,39 @@ pub fn migrate_blob_db(pool: &SqlitePool) -> Result<()> {
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
use crate::error::Error;
|
||||||
|
|
||||||
fn create_test_pool() -> SqlitePool {
|
fn create_test_manager() -> BlobManager {
|
||||||
let manager = r2d2_sqlite::SqliteConnectionManager::memory();
|
let manager = r2d2_sqlite::SqliteConnectionManager::memory();
|
||||||
let pool = r2d2::Pool::builder().max_size(1).build(manager).unwrap();
|
let pool = r2d2::Pool::builder().max_size(1).build(manager).unwrap();
|
||||||
migrate_blob_db(&pool).unwrap();
|
migrate_blob_db(&pool).unwrap();
|
||||||
pool
|
BlobManager::new(pool.clone(), pool)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn insert(manager: &BlobManager, chunks: &[BodyChunk]) {
|
||||||
|
manager
|
||||||
|
.with_tx(|b| {
|
||||||
|
for c in chunks {
|
||||||
|
b.insert_chunk(c)?;
|
||||||
|
}
|
||||||
|
Ok::<_, Error>(())
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_insert_and_get_chunks() {
|
fn test_insert_and_get_chunks() {
|
||||||
let pool = create_test_pool();
|
let manager = create_test_manager();
|
||||||
let manager = BlobManager::new(pool);
|
|
||||||
let ctx = manager.connect();
|
|
||||||
|
|
||||||
let body_id = "rs_test123.request";
|
let body_id = "rs_test123.request";
|
||||||
let chunk1 = BodyChunk::new(body_id, 0, b"Hello, ".to_vec());
|
insert(
|
||||||
let chunk2 = BodyChunk::new(body_id, 1, b"World!".to_vec());
|
&manager,
|
||||||
|
&[
|
||||||
|
BodyChunk::new(body_id, 0, b"Hello, ".to_vec()),
|
||||||
|
BodyChunk::new(body_id, 1, b"World!".to_vec()),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
|
||||||
ctx.insert_chunk(&chunk1).unwrap();
|
let chunks = manager.connect().get_chunks(body_id).unwrap();
|
||||||
ctx.insert_chunk(&chunk2).unwrap();
|
|
||||||
|
|
||||||
let chunks = ctx.get_chunks(body_id).unwrap();
|
|
||||||
assert_eq!(chunks.len(), 2);
|
assert_eq!(chunks.len(), 2);
|
||||||
assert_eq!(chunks[0].chunk_index, 0);
|
assert_eq!(chunks[0].chunk_index, 0);
|
||||||
assert_eq!(chunks[0].data, b"Hello, ");
|
assert_eq!(chunks[0].data, b"Hello, ");
|
||||||
@@ -227,18 +288,19 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_get_chunks_ordered_by_index() {
|
fn test_get_chunks_ordered_by_index() {
|
||||||
let pool = create_test_pool();
|
let manager = create_test_manager();
|
||||||
let manager = BlobManager::new(pool);
|
|
||||||
let ctx = manager.connect();
|
|
||||||
|
|
||||||
let body_id = "rs_test123.request";
|
let body_id = "rs_test123.request";
|
||||||
|
|
||||||
// Insert out of order
|
// Insert out of order
|
||||||
ctx.insert_chunk(&BodyChunk::new(body_id, 2, b"C".to_vec())).unwrap();
|
insert(
|
||||||
ctx.insert_chunk(&BodyChunk::new(body_id, 0, b"A".to_vec())).unwrap();
|
&manager,
|
||||||
ctx.insert_chunk(&BodyChunk::new(body_id, 1, b"B".to_vec())).unwrap();
|
&[
|
||||||
|
BodyChunk::new(body_id, 2, b"C".to_vec()),
|
||||||
|
BodyChunk::new(body_id, 0, b"A".to_vec()),
|
||||||
|
BodyChunk::new(body_id, 1, b"B".to_vec()),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
|
||||||
let chunks = ctx.get_chunks(body_id).unwrap();
|
let chunks = manager.connect().get_chunks(body_id).unwrap();
|
||||||
assert_eq!(chunks.len(), 3);
|
assert_eq!(chunks.len(), 3);
|
||||||
assert_eq!(chunks[0].data, b"A");
|
assert_eq!(chunks[0].data, b"A");
|
||||||
assert_eq!(chunks[1].data, b"B");
|
assert_eq!(chunks[1].data, b"B");
|
||||||
@@ -247,89 +309,85 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_delete_chunks() {
|
fn test_delete_chunks() {
|
||||||
let pool = create_test_pool();
|
let manager = create_test_manager();
|
||||||
let manager = BlobManager::new(pool);
|
|
||||||
let ctx = manager.connect();
|
|
||||||
|
|
||||||
let body_id = "rs_test123.request";
|
let body_id = "rs_test123.request";
|
||||||
ctx.insert_chunk(&BodyChunk::new(body_id, 0, b"data".to_vec())).unwrap();
|
insert(&manager, &[BodyChunk::new(body_id, 0, b"data".to_vec())]);
|
||||||
|
assert!(manager.connect().body_exists(body_id).unwrap());
|
||||||
|
|
||||||
assert!(ctx.body_exists(body_id).unwrap());
|
manager.with_tx(|b| b.delete_chunks(body_id)).unwrap();
|
||||||
|
|
||||||
ctx.delete_chunks(body_id).unwrap();
|
|
||||||
|
|
||||||
|
let ctx = manager.connect();
|
||||||
assert!(!ctx.body_exists(body_id).unwrap());
|
assert!(!ctx.body_exists(body_id).unwrap());
|
||||||
assert_eq!(ctx.get_chunks(body_id).unwrap().len(), 0);
|
assert_eq!(ctx.get_chunks(body_id).unwrap().len(), 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_delete_chunks_like() {
|
fn test_delete_chunks_like() {
|
||||||
let pool = create_test_pool();
|
let manager = create_test_manager();
|
||||||
let manager = BlobManager::new(pool);
|
|
||||||
let ctx = manager.connect();
|
|
||||||
|
|
||||||
// Insert chunks for same response but different body types
|
// Insert chunks for same response but different body types
|
||||||
ctx.insert_chunk(&BodyChunk::new("rs_abc.request", 0, b"req".to_vec())).unwrap();
|
insert(
|
||||||
ctx.insert_chunk(&BodyChunk::new("rs_abc.response", 0, b"resp".to_vec())).unwrap();
|
&manager,
|
||||||
ctx.insert_chunk(&BodyChunk::new("rs_other.request", 0, b"other".to_vec())).unwrap();
|
&[
|
||||||
|
BodyChunk::new("rs_abc.request", 0, b"req".to_vec()),
|
||||||
|
BodyChunk::new("rs_abc.response", 0, b"resp".to_vec()),
|
||||||
|
BodyChunk::new("rs_other.request", 0, b"other".to_vec()),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
|
||||||
// Delete all bodies for rs_abc
|
// Delete all bodies for rs_abc
|
||||||
ctx.delete_chunks_like("rs_abc.%").unwrap();
|
manager.with_tx(|b| b.delete_chunks_like("rs_abc.%")).unwrap();
|
||||||
|
|
||||||
// rs_abc bodies should be gone
|
let ctx = manager.connect();
|
||||||
assert!(!ctx.body_exists("rs_abc.request").unwrap());
|
assert!(!ctx.body_exists("rs_abc.request").unwrap());
|
||||||
assert!(!ctx.body_exists("rs_abc.response").unwrap());
|
assert!(!ctx.body_exists("rs_abc.response").unwrap());
|
||||||
|
|
||||||
// rs_other should still exist
|
|
||||||
assert!(ctx.body_exists("rs_other.request").unwrap());
|
assert!(ctx.body_exists("rs_other.request").unwrap());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_get_body_size() {
|
fn test_get_body_size() {
|
||||||
let pool = create_test_pool();
|
let manager = create_test_manager();
|
||||||
let manager = BlobManager::new(pool);
|
|
||||||
let ctx = manager.connect();
|
|
||||||
|
|
||||||
let body_id = "rs_test123.request";
|
let body_id = "rs_test123.request";
|
||||||
ctx.insert_chunk(&BodyChunk::new(body_id, 0, b"Hello".to_vec())).unwrap();
|
insert(
|
||||||
ctx.insert_chunk(&BodyChunk::new(body_id, 1, b"World".to_vec())).unwrap();
|
&manager,
|
||||||
|
&[
|
||||||
|
BodyChunk::new(body_id, 0, b"Hello".to_vec()),
|
||||||
|
BodyChunk::new(body_id, 1, b"World".to_vec()),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
|
||||||
let size = ctx.get_body_size(body_id).unwrap();
|
let size = manager.connect().get_body_size(body_id).unwrap();
|
||||||
assert_eq!(size, 10); // "Hello" + "World" = 10 bytes
|
assert_eq!(size, 10); // "Hello" + "World" = 10 bytes
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_get_body_size_empty() {
|
fn test_get_body_size_empty() {
|
||||||
let pool = create_test_pool();
|
let manager = create_test_manager();
|
||||||
let manager = BlobManager::new(pool);
|
let size = manager.connect().get_body_size("nonexistent").unwrap();
|
||||||
let ctx = manager.connect();
|
|
||||||
|
|
||||||
let size = ctx.get_body_size("nonexistent").unwrap();
|
|
||||||
assert_eq!(size, 0);
|
assert_eq!(size, 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_body_exists() {
|
fn test_body_exists() {
|
||||||
let pool = create_test_pool();
|
let manager = create_test_manager();
|
||||||
let manager = BlobManager::new(pool);
|
assert!(!manager.connect().body_exists("rs_test.request").unwrap());
|
||||||
let ctx = manager.connect();
|
|
||||||
|
|
||||||
assert!(!ctx.body_exists("rs_test.request").unwrap());
|
insert(&manager, &[BodyChunk::new("rs_test.request", 0, b"data".to_vec())]);
|
||||||
|
|
||||||
ctx.insert_chunk(&BodyChunk::new("rs_test.request", 0, b"data".to_vec())).unwrap();
|
assert!(manager.connect().body_exists("rs_test.request").unwrap());
|
||||||
|
|
||||||
assert!(ctx.body_exists("rs_test.request").unwrap());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_multiple_bodies_isolated() {
|
fn test_multiple_bodies_isolated() {
|
||||||
let pool = create_test_pool();
|
let manager = create_test_manager();
|
||||||
let manager = BlobManager::new(pool);
|
insert(
|
||||||
|
&manager,
|
||||||
|
&[
|
||||||
|
BodyChunk::new("body1", 0, b"data1".to_vec()),
|
||||||
|
BodyChunk::new("body2", 0, b"data2".to_vec()),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
|
||||||
let ctx = manager.connect();
|
let ctx = manager.connect();
|
||||||
|
|
||||||
ctx.insert_chunk(&BodyChunk::new("body1", 0, b"data1".to_vec())).unwrap();
|
|
||||||
ctx.insert_chunk(&BodyChunk::new("body2", 0, b"data2".to_vec())).unwrap();
|
|
||||||
|
|
||||||
let chunks1 = ctx.get_chunks("body1").unwrap();
|
let chunks1 = ctx.get_chunks("body1").unwrap();
|
||||||
let chunks2 = ctx.get_chunks("body2").unwrap();
|
let chunks2 = ctx.get_chunks("body2").unwrap();
|
||||||
|
|
||||||
@@ -341,16 +399,13 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_large_chunk() {
|
fn test_large_chunk() {
|
||||||
let pool = create_test_pool();
|
let manager = create_test_manager();
|
||||||
let manager = BlobManager::new(pool);
|
|
||||||
let ctx = manager.connect();
|
|
||||||
|
|
||||||
// 1MB chunk
|
// 1MB chunk
|
||||||
let large_data: Vec<u8> = (0..1024 * 1024).map(|i| (i % 256) as u8).collect();
|
let large_data: Vec<u8> = (0..1024 * 1024).map(|i| (i % 256) as u8).collect();
|
||||||
let body_id = "rs_large.request";
|
let body_id = "rs_large.request";
|
||||||
|
insert(&manager, &[BodyChunk::new(body_id, 0, large_data.clone())]);
|
||||||
|
|
||||||
ctx.insert_chunk(&BodyChunk::new(body_id, 0, large_data.clone())).unwrap();
|
let ctx = manager.connect();
|
||||||
|
|
||||||
let chunks = ctx.get_chunks(body_id).unwrap();
|
let chunks = ctx.get_chunks(body_id).unwrap();
|
||||||
assert_eq!(chunks.len(), 1);
|
assert_eq!(chunks.len(), 1);
|
||||||
assert_eq!(chunks[0].data, large_data);
|
assert_eq!(chunks[0].data, large_data);
|
||||||
|
|||||||
@@ -3,18 +3,25 @@ use crate::models::{AnyModel, UpsertModelInfo};
|
|||||||
use crate::util::{ModelChangeEvent, ModelPayload, UpdateSource};
|
use crate::util::{ModelChangeEvent, ModelPayload, UpdateSource};
|
||||||
use rusqlite::params;
|
use rusqlite::params;
|
||||||
use sea_query::{IntoColumnRef, IntoIden, SimpleExpr};
|
use sea_query::{IntoColumnRef, IntoIden, SimpleExpr};
|
||||||
|
use std::cell::RefCell;
|
||||||
use std::fmt::Debug;
|
use std::fmt::Debug;
|
||||||
|
use std::ops::Deref;
|
||||||
use std::sync::mpsc;
|
use std::sync::mpsc;
|
||||||
use yaak_database::DbContext;
|
use yaak_database::DbContext;
|
||||||
|
|
||||||
|
/// A read handle. Comes from the reader pool and can only query.
|
||||||
|
///
|
||||||
|
/// Anything that changes a row lives on [`WriteDb`], which is only ever handed
|
||||||
|
/// out inside a transaction on the single writer connection. That split is
|
||||||
|
/// what keeps the pool from filling with writers waiting on each other: there
|
||||||
|
/// is one writer, so there is never a second one to wait for.
|
||||||
pub struct ClientDb<'a> {
|
pub struct ClientDb<'a> {
|
||||||
pub(crate) ctx: DbContext<'a>,
|
pub(crate) ctx: DbContext<'a>,
|
||||||
pub(crate) events_tx: mpsc::Sender<ModelPayload>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> ClientDb<'a> {
|
impl<'a> ClientDb<'a> {
|
||||||
pub fn new(ctx: DbContext<'a>, events_tx: mpsc::Sender<ModelPayload>) -> Self {
|
pub fn new(ctx: DbContext<'a>) -> Self {
|
||||||
Self { ctx, events_tx }
|
Self { ctx }
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Access the underlying connection for custom queries.
|
/// Access the underlying connection for custom queries.
|
||||||
@@ -22,8 +29,6 @@ impl<'a> ClientDb<'a> {
|
|||||||
self.ctx.conn()
|
self.ctx.conn()
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- Read delegates (thin wrappers over DbContext) ---
|
|
||||||
|
|
||||||
pub(crate) fn find_one<M>(
|
pub(crate) fn find_one<M>(
|
||||||
&self,
|
&self,
|
||||||
col: impl IntoColumnRef + IntoIden + Clone,
|
col: impl IntoColumnRef + IntoIden + Clone,
|
||||||
@@ -64,6 +69,39 @@ impl<'a> ClientDb<'a> {
|
|||||||
{
|
{
|
||||||
Ok(self.ctx.find_many(col, value, limit)?)
|
Ok(self.ctx.find_many(col, value, limit)?)
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A write handle: a [`ClientDb`] on the writer connection, inside a
|
||||||
|
/// transaction, that can also change rows. Derefs to [`ClientDb`] so every
|
||||||
|
/// query is available while writing, and reads inside the transaction see
|
||||||
|
/// its own uncommitted writes.
|
||||||
|
///
|
||||||
|
/// Model events are held back until the transaction commits; a rollback
|
||||||
|
/// discards them along with the rows.
|
||||||
|
pub struct WriteDb<'a> {
|
||||||
|
db: ClientDb<'a>,
|
||||||
|
events_tx: mpsc::Sender<ModelPayload>,
|
||||||
|
pending_events: RefCell<Vec<ModelPayload>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> Deref for WriteDb<'a> {
|
||||||
|
type Target = ClientDb<'a>;
|
||||||
|
|
||||||
|
fn deref(&self) -> &ClientDb<'a> {
|
||||||
|
&self.db
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> WriteDb<'a> {
|
||||||
|
pub fn new(ctx: DbContext<'a>, events_tx: mpsc::Sender<ModelPayload>) -> Self {
|
||||||
|
Self { db: ClientDb::new(ctx), events_tx, pending_events: RefCell::new(Vec::new()) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The events for everything written so far, to send once the
|
||||||
|
/// transaction has committed.
|
||||||
|
pub(crate) fn into_events(self) -> Vec<ModelPayload> {
|
||||||
|
self.pending_events.into_inner()
|
||||||
|
}
|
||||||
|
|
||||||
/// Bulk-delete all rows matching a column value WITHOUT recording model
|
/// Bulk-delete all rows matching a column value WITHOUT recording model
|
||||||
/// changes or emitting events. Only use for cascades whose deletion is
|
/// changes or emitting events. Only use for cascades whose deletion is
|
||||||
@@ -80,8 +118,6 @@ impl<'a> ClientDb<'a> {
|
|||||||
Ok(self.ctx.delete_many::<M>(col, value)?)
|
Ok(self.ctx.delete_many::<M>(col, value)?)
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- Write operations (with event recording) ---
|
|
||||||
|
|
||||||
pub(crate) fn upsert<M>(&self, model: &M, source: &UpdateSource) -> Result<M>
|
pub(crate) fn upsert<M>(&self, model: &M, source: &UpdateSource) -> Result<M>
|
||||||
where
|
where
|
||||||
M: Into<AnyModel> + UpsertModelInfo + Clone,
|
M: Into<AnyModel> + UpsertModelInfo + Clone,
|
||||||
@@ -95,7 +131,7 @@ impl<'a> ClientDb<'a> {
|
|||||||
};
|
};
|
||||||
|
|
||||||
self.record_model_change(&payload)?;
|
self.record_model_change(&payload)?;
|
||||||
let _ = self.events_tx.send(payload);
|
self.pending_events.borrow_mut().push(payload);
|
||||||
|
|
||||||
Ok(m)
|
Ok(m)
|
||||||
}
|
}
|
||||||
@@ -113,7 +149,7 @@ impl<'a> ClientDb<'a> {
|
|||||||
};
|
};
|
||||||
|
|
||||||
self.record_model_change(&payload)?;
|
self.record_model_change(&payload)?;
|
||||||
let _ = self.events_tx.send(payload);
|
self.pending_events.borrow_mut().push(payload);
|
||||||
|
|
||||||
Ok(m.clone())
|
Ok(m.clone())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,8 +10,8 @@ use yaak_database::SqlitePool;
|
|||||||
|
|
||||||
pub mod blob_manager;
|
pub mod blob_manager;
|
||||||
pub mod client_db;
|
pub mod client_db;
|
||||||
pub mod cookies;
|
|
||||||
mod connection_or_tx;
|
mod connection_or_tx;
|
||||||
|
pub mod cookies;
|
||||||
pub mod error;
|
pub mod error;
|
||||||
pub mod migrate;
|
pub mod migrate;
|
||||||
pub mod models;
|
pub mod models;
|
||||||
@@ -64,6 +64,17 @@ mod open {
|
|||||||
.map_err(|e| Error::Database(e.to_string()))
|
.map_err(|e| Error::Database(e.to_string()))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// `(readers, writer)` over one file: a pool of `max_size` readers and a
|
||||||
|
/// pool of exactly one writer.
|
||||||
|
pub fn file_pools(
|
||||||
|
path: impl Into<PathBuf>,
|
||||||
|
max_size: u32,
|
||||||
|
min_idle: u32,
|
||||||
|
) -> Result<(SqlitePool, SqlitePool)> {
|
||||||
|
let path: PathBuf = path.into();
|
||||||
|
Ok((file_pool(&path, max_size, min_idle)?, file_pool(&path, 1, 1)?))
|
||||||
|
}
|
||||||
|
|
||||||
pub fn memory_pool() -> Result<SqlitePool> {
|
pub fn memory_pool() -> Result<SqlitePool> {
|
||||||
let manager = SqliteConnectionManager::memory().with_init(|c| init_connection(c));
|
let manager = SqliteConnectionManager::memory().with_init(|c| init_connection(c));
|
||||||
// In-memory DB doesn't support multiple connections
|
// In-memory DB doesn't support multiple connections
|
||||||
@@ -90,6 +101,16 @@ mod open {
|
|||||||
Ok(SqlitePool::single(conn))
|
Ok(SqlitePool::single(conn))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// One connection is all a browser VFS allows, so it reads and writes.
|
||||||
|
pub fn file_pools(
|
||||||
|
path: impl Into<PathBuf>,
|
||||||
|
max_size: u32,
|
||||||
|
min_idle: u32,
|
||||||
|
) -> Result<(SqlitePool, SqlitePool)> {
|
||||||
|
let pool = file_pool(path, max_size, min_idle)?;
|
||||||
|
Ok((pool.clone(), pool))
|
||||||
|
}
|
||||||
|
|
||||||
pub fn memory_pool() -> Result<SqlitePool> {
|
pub fn memory_pool() -> Result<SqlitePool> {
|
||||||
let conn = Connection::open_in_memory()?;
|
let conn = Connection::open_in_memory()?;
|
||||||
init_connection(&conn)?;
|
init_connection(&conn)?;
|
||||||
@@ -108,27 +129,33 @@ pub fn init_standalone(
|
|||||||
let db_path = db_path.as_ref();
|
let db_path = db_path.as_ref();
|
||||||
let blob_path = blob_path.as_ref();
|
let blob_path = blob_path.as_ref();
|
||||||
|
|
||||||
// Main database pool. Sized for concurrent in-flight queries, not concurrent app
|
// Each database gets a reader pool and a one-connection writer pool; see
|
||||||
// features — connections are held per-statement, so even heavy fan-out (e.g. many
|
// `QueryManager` for why. Reader pools are sized for concurrent in-flight
|
||||||
// gRPC streams) only needs a handful at once. Keep max_size modest: WAL connections
|
// queries, not concurrent app features — connections are held per-statement,
|
||||||
// hold ~3 file descriptors each, and macOS GUI apps get a 256 fd soft limit.
|
// so even heavy fan-out (e.g. many gRPC streams) only needs a handful at once.
|
||||||
|
// Keep them modest: WAL connections hold ~3 file descriptors each, and macOS
|
||||||
|
// GUI apps get a 256 fd soft limit.
|
||||||
info!("Initializing app database {db_path:?}");
|
info!("Initializing app database {db_path:?}");
|
||||||
let pool = open::file_pool(db_path, 20, 2)?;
|
let (readers, writer) = open::file_pools(db_path, 20, 2)?;
|
||||||
migrate_db(&pool)?;
|
migrate_db(&writer)?;
|
||||||
|
|
||||||
info!("Initializing blobs database {blob_path:?}");
|
info!("Initializing blobs database {blob_path:?}");
|
||||||
let blob_pool = open::file_pool(blob_path, 10, 1)?;
|
let (blob_readers, blob_writer) = open::file_pools(blob_path, 10, 1)?;
|
||||||
migrate_blob_db(&blob_pool)?;
|
migrate_blob_db(&blob_writer)?;
|
||||||
|
|
||||||
let (tx, rx) = mpsc::channel();
|
let (tx, rx) = mpsc::channel();
|
||||||
let query_manager = QueryManager::new(pool, tx);
|
let query_manager = QueryManager::new(readers, writer, tx);
|
||||||
let blob_manager = BlobManager::new(blob_pool);
|
let blob_manager = BlobManager::new(blob_readers, blob_writer);
|
||||||
|
bootstrap(&query_manager)?;
|
||||||
|
|
||||||
Ok((query_manager, blob_manager, rx))
|
Ok((query_manager, blob_manager, rx))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Initialize the database managers with in-memory SQLite databases.
|
/// Initialize the database managers with in-memory SQLite databases.
|
||||||
/// Useful for testing and CI environments.
|
/// Useful for testing and CI environments.
|
||||||
|
///
|
||||||
|
/// An in-memory database is private to its connection, so the one connection
|
||||||
|
/// is both the reader pool and the writer.
|
||||||
pub fn init_in_memory() -> Result<(QueryManager, BlobManager, mpsc::Receiver<ModelPayload>)> {
|
pub fn init_in_memory() -> Result<(QueryManager, BlobManager, mpsc::Receiver<ModelPayload>)> {
|
||||||
let pool = open::memory_pool()?;
|
let pool = open::memory_pool()?;
|
||||||
migrate_db(&pool)?;
|
migrate_db(&pool)?;
|
||||||
@@ -137,8 +164,18 @@ pub fn init_in_memory() -> Result<(QueryManager, BlobManager, mpsc::Receiver<Mod
|
|||||||
migrate_blob_db(&blob_pool)?;
|
migrate_blob_db(&blob_pool)?;
|
||||||
|
|
||||||
let (tx, rx) = mpsc::channel();
|
let (tx, rx) = mpsc::channel();
|
||||||
let query_manager = QueryManager::new(pool, tx);
|
let query_manager = QueryManager::new(pool.clone(), pool, tx);
|
||||||
let blob_manager = BlobManager::new(blob_pool);
|
let blob_manager = BlobManager::new(blob_pool.clone(), blob_pool);
|
||||||
|
bootstrap(&query_manager)?;
|
||||||
|
|
||||||
Ok((query_manager, blob_manager, rx))
|
Ok((query_manager, blob_manager, rx))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The rows every client assumes exist: settings and at least one workspace.
|
||||||
|
fn bootstrap(query_manager: &QueryManager) -> Result<()> {
|
||||||
|
query_manager.with_tx(|tx| {
|
||||||
|
tx.ensure_settings()?;
|
||||||
|
tx.ensure_default_workspace()?;
|
||||||
|
Ok(())
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -3118,8 +3118,12 @@ pub struct ImportSourceResource {
|
|||||||
pub import_source_id: String,
|
pub import_source_id: String,
|
||||||
pub source_key: String,
|
pub source_key: String,
|
||||||
pub model_type: String,
|
pub model_type: String,
|
||||||
pub model_id: String,
|
/// `None` once the user has decided not to import this key
|
||||||
pub snapshot: String,
|
#[ts(optional)]
|
||||||
|
pub model_id: Option<String>,
|
||||||
|
/// Hash of the resource as last applied or decided from the source, if one was recorded
|
||||||
|
#[ts(optional)]
|
||||||
|
pub content_hash: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'s> TryFrom<&Row<'s>> for ImportSourceResource {
|
impl<'s> TryFrom<&Row<'s>> for ImportSourceResource {
|
||||||
@@ -3134,7 +3138,7 @@ impl<'s> TryFrom<&Row<'s>> for ImportSourceResource {
|
|||||||
source_key: r.get("source_key")?,
|
source_key: r.get("source_key")?,
|
||||||
model_type: r.get("model_type")?,
|
model_type: r.get("model_type")?,
|
||||||
model_id: r.get("model_id")?,
|
model_id: r.get("model_id")?,
|
||||||
snapshot: r.get("snapshot")?,
|
content_hash: r.get("content_hash")?,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,14 +8,14 @@
|
|||||||
//! caller is a desktop window or an HTTP request.
|
//! caller is a desktop window or an HTTP request.
|
||||||
|
|
||||||
use crate::blob_manager::BlobManager;
|
use crate::blob_manager::BlobManager;
|
||||||
use crate::client_db::ClientDb;
|
use crate::client_db::WriteDb;
|
||||||
use crate::error::Error::GenericError;
|
use crate::error::Error::GenericError;
|
||||||
use crate::error::Result;
|
use crate::error::Result;
|
||||||
use crate::models::AnyModel;
|
use crate::models::AnyModel;
|
||||||
use crate::util::UpdateSource;
|
use crate::util::UpdateSource;
|
||||||
|
|
||||||
pub fn upsert_model(
|
pub fn upsert_model(
|
||||||
db: &ClientDb,
|
db: &WriteDb,
|
||||||
blobs: &BlobManager,
|
blobs: &BlobManager,
|
||||||
model: AnyModel,
|
model: AnyModel,
|
||||||
source: &UpdateSource,
|
source: &UpdateSource,
|
||||||
@@ -41,7 +41,7 @@ pub fn upsert_model(
|
|||||||
|
|
||||||
/// Deletes cascade, so callers run this inside a transaction.
|
/// Deletes cascade, so callers run this inside a transaction.
|
||||||
pub fn delete_model(
|
pub fn delete_model(
|
||||||
tx: &ClientDb,
|
tx: &WriteDb,
|
||||||
blobs: &BlobManager,
|
blobs: &BlobManager,
|
||||||
model: AnyModel,
|
model: AnyModel,
|
||||||
source: &UpdateSource,
|
source: &UpdateSource,
|
||||||
@@ -69,7 +69,7 @@ pub fn delete_model(
|
|||||||
/// The model is re-read from the database rather than taken from the caller, so
|
/// The model is re-read from the database rather than taken from the caller, so
|
||||||
/// a duplicate never comes from a stale frontend snapshot.
|
/// a duplicate never comes from a stale frontend snapshot.
|
||||||
pub fn duplicate_model(
|
pub fn duplicate_model(
|
||||||
tx: &ClientDb,
|
tx: &WriteDb,
|
||||||
model_type: &str,
|
model_type: &str,
|
||||||
model_id: &str,
|
model_id: &str,
|
||||||
source: &UpdateSource,
|
source: &UpdateSource,
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
use crate::client_db::ClientDb;
|
use crate::client_db::WriteDb;
|
||||||
use crate::error::Result;
|
use crate::error::Result;
|
||||||
use crate::models::{Environment, Folder, GrpcRequest, HttpRequest, WebsocketRequest, Workspace};
|
use crate::models::{Environment, Folder, GrpcRequest, HttpRequest, WebsocketRequest, Workspace};
|
||||||
use crate::util::{BatchUpsertResult, UpdateSource};
|
use crate::util::{BatchUpsertResult, UpdateSource};
|
||||||
use log::info;
|
use log::info;
|
||||||
|
|
||||||
impl<'a> ClientDb<'a> {
|
impl<'a> WriteDb<'a> {
|
||||||
pub fn batch_upsert(
|
pub fn batch_upsert(
|
||||||
&self,
|
&self,
|
||||||
workspaces: Vec<Workspace>,
|
workspaces: Vec<Workspace>,
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
use crate::client_db::ClientDb;
|
use crate::client_db::{ClientDb, WriteDb};
|
||||||
use crate::error::Result;
|
use crate::error::Result;
|
||||||
use crate::models::{CookieJar, CookieJarIden};
|
use crate::models::{CookieJar, CookieJarIden};
|
||||||
use crate::util::UpdateSource;
|
use crate::util::UpdateSource;
|
||||||
@@ -9,18 +9,22 @@ impl<'a> ClientDb<'a> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn list_cookie_jars(&self, workspace_id: &str) -> Result<Vec<CookieJar>> {
|
pub fn list_cookie_jars(&self, workspace_id: &str) -> Result<Vec<CookieJar>> {
|
||||||
let mut cookie_jars = self.find_many(CookieJarIden::WorkspaceId, workspace_id, None)?;
|
self.find_many(CookieJarIden::WorkspaceId, workspace_id, None)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if cookie_jars.is_empty() {
|
impl<'a> WriteDb<'a> {
|
||||||
|
/// A workspace with no cookie jar gets a default one.
|
||||||
|
pub fn ensure_default_cookie_jar(&self, workspace_id: &str) -> Result<()> {
|
||||||
|
if self.list_cookie_jars(workspace_id)?.is_empty() {
|
||||||
let jar = CookieJar {
|
let jar = CookieJar {
|
||||||
name: "Default".to_string(),
|
name: "Default".to_string(),
|
||||||
workspace_id: workspace_id.to_string(),
|
workspace_id: workspace_id.to_string(),
|
||||||
..Default::default()
|
..Default::default()
|
||||||
};
|
};
|
||||||
cookie_jars.push(self.upsert_cookie_jar(&jar, &UpdateSource::Background)?);
|
self.upsert_cookie_jar(&jar, &UpdateSource::Background)?;
|
||||||
}
|
}
|
||||||
|
Ok(())
|
||||||
Ok(cookie_jars)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn delete_cookie_jar(
|
pub fn delete_cookie_jar(
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
use super::conflict_free_name;
|
use super::conflict_free_name;
|
||||||
use crate::client_db::ClientDb;
|
use crate::client_db::{ClientDb, WriteDb};
|
||||||
use crate::error::Error::{MissingBaseEnvironment, MultipleBaseEnvironments};
|
use crate::error::Error::{MissingBaseEnvironment, MultipleBaseEnvironments};
|
||||||
use crate::error::Result;
|
use crate::error::Result;
|
||||||
use crate::models::{Environment, EnvironmentIden, EnvironmentVariable};
|
use crate::models::{Environment, EnvironmentIden, EnvironmentVariable};
|
||||||
@@ -20,7 +20,7 @@ impl<'a> ClientDb<'a> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn get_base_environment(&self, workspace_id: &str) -> Result<Environment> {
|
pub fn get_base_environment(&self, workspace_id: &str) -> Result<Environment> {
|
||||||
let environments = self.list_environments_ensure_base(workspace_id)?;
|
let environments = self.list_environments(workspace_id)?;
|
||||||
let base_environments = environments
|
let base_environments = environments
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.filter(|e| e.parent_model == "workspace")
|
.filter(|e| e.parent_model == "workspace")
|
||||||
@@ -30,38 +30,96 @@ impl<'a> ClientDb<'a> {
|
|||||||
return Err(MultipleBaseEnvironments(workspace_id.to_string()));
|
return Err(MultipleBaseEnvironments(workspace_id.to_string()));
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(base_environments.first().cloned().ok_or(
|
Ok(base_environments
|
||||||
// Should never happen because one should be created above if it does not exist
|
.first()
|
||||||
MissingBaseEnvironment(workspace_id.to_string()),
|
.cloned()
|
||||||
)?)
|
.ok_or(MissingBaseEnvironment(workspace_id.to_string()))?)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Lists environments and will create a base environment if one doesn't exist
|
pub fn list_environments(&self, workspace_id: &str) -> Result<Vec<Environment>> {
|
||||||
pub fn list_environments_ensure_base(&self, workspace_id: &str) -> Result<Vec<Environment>> {
|
Ok(self.find_many::<Environment>(EnvironmentIden::WorkspaceId, workspace_id, None)?)
|
||||||
let mut environments = self.list_environments_dangerous(workspace_id)?;
|
}
|
||||||
|
|
||||||
let base_environment = environments.iter().find(|e| e.parent_model == "workspace");
|
/// Find other environments with the same parent folder
|
||||||
|
fn list_duplicate_folder_environments(&self, environment: &Environment) -> Vec<Environment> {
|
||||||
|
if environment.parent_model != "folder" {
|
||||||
|
return Vec::new();
|
||||||
|
}
|
||||||
|
|
||||||
if let None = base_environment {
|
self.list_environments(&environment.workspace_id)
|
||||||
let e = self.upsert_environment(
|
.unwrap_or_default()
|
||||||
&Environment {
|
.into_iter()
|
||||||
workspace_id: workspace_id.to_string(),
|
.filter(|e| {
|
||||||
name: "Global Variables".to_string(),
|
e.id != environment.id
|
||||||
parent_model: "workspace".to_string(),
|
&& e.parent_model == "folder"
|
||||||
..Default::default()
|
&& e.parent_id == environment.parent_id
|
||||||
},
|
})
|
||||||
&UpdateSource::Background,
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn resolve_environments(
|
||||||
|
&self,
|
||||||
|
workspace_id: &str,
|
||||||
|
folder_id: Option<&str>,
|
||||||
|
active_environment_id: Option<&str>,
|
||||||
|
) -> Result<Vec<Environment>> {
|
||||||
|
let mut environments = Vec::new();
|
||||||
|
|
||||||
|
if let Some(folder_id) = folder_id {
|
||||||
|
let folder = self.get_folder(folder_id)?;
|
||||||
|
|
||||||
|
// Add current folder's environment
|
||||||
|
if let Some(e) = self.get_environment_by_folder_id(folder_id)? {
|
||||||
|
environments.push(e);
|
||||||
|
};
|
||||||
|
|
||||||
|
// Recurse up
|
||||||
|
let ancestors = self.resolve_environments(
|
||||||
|
workspace_id,
|
||||||
|
folder.folder_id.as_deref(),
|
||||||
|
active_environment_id,
|
||||||
)?;
|
)?;
|
||||||
info!("Created base environment {} for {workspace_id}", e.id);
|
environments.extend(ancestors);
|
||||||
environments.push(e);
|
} else {
|
||||||
|
// Add active and base environments
|
||||||
|
if let Some(id) = active_environment_id {
|
||||||
|
if let Ok(e) = self.get_environment(&id) {
|
||||||
|
// Add active sub environment
|
||||||
|
environments.push(e);
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
// Add the base environment. A workspace that has never been
|
||||||
|
// opened has none yet; it simply contributes no variables.
|
||||||
|
match self.get_base_environment(workspace_id) {
|
||||||
|
Ok(e) => environments.push(e),
|
||||||
|
Err(MissingBaseEnvironment(_)) => {}
|
||||||
|
Err(e) => return Err(e),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(environments)
|
Ok(environments)
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// List environments for a workspace. Prefer list_environments_ensure_base()
|
impl<'a> WriteDb<'a> {
|
||||||
fn list_environments_dangerous(&self, workspace_id: &str) -> Result<Vec<Environment>> {
|
/// The workspace's base environment, created if it does not exist.
|
||||||
Ok(self.find_many::<Environment>(EnvironmentIden::WorkspaceId, workspace_id, None)?)
|
pub fn ensure_base_environment(&self, workspace_id: &str) -> Result<Environment> {
|
||||||
|
match self.get_base_environment(workspace_id) {
|
||||||
|
Err(MissingBaseEnvironment(_)) => {}
|
||||||
|
other => return other,
|
||||||
|
}
|
||||||
|
let e = self.upsert_environment(
|
||||||
|
&Environment {
|
||||||
|
workspace_id: workspace_id.to_string(),
|
||||||
|
name: "Global Variables".to_string(),
|
||||||
|
parent_model: "workspace".to_string(),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
&UpdateSource::Background,
|
||||||
|
)?;
|
||||||
|
info!("Created base environment {} for {workspace_id}", e.id);
|
||||||
|
Ok(e)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn delete_environment(
|
pub fn delete_environment(
|
||||||
@@ -72,7 +130,7 @@ impl<'a> ClientDb<'a> {
|
|||||||
let deleted_environment = self.delete(environment, source)?;
|
let deleted_environment = self.delete(environment, source)?;
|
||||||
|
|
||||||
// Recreate the base environment if we happened to delete it
|
// Recreate the base environment if we happened to delete it
|
||||||
self.list_environments_ensure_base(&environment.workspace_id)?;
|
self.ensure_base_environment(&environment.workspace_id)?;
|
||||||
|
|
||||||
Ok(deleted_environment)
|
Ok(deleted_environment)
|
||||||
}
|
}
|
||||||
@@ -90,7 +148,7 @@ impl<'a> ClientDb<'a> {
|
|||||||
let mut environment = environment.clone();
|
let mut environment = environment.clone();
|
||||||
environment.id = "".to_string();
|
environment.id = "".to_string();
|
||||||
let sibling_names = self
|
let sibling_names = self
|
||||||
.list_environments_dangerous(&environment.workspace_id)?
|
.list_environments(&environment.workspace_id)?
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|e| e.name)
|
.map(|e| e.name)
|
||||||
.collect::<Vec<_>>();
|
.collect::<Vec<_>>();
|
||||||
@@ -98,23 +156,6 @@ impl<'a> ClientDb<'a> {
|
|||||||
self.upsert_environment(&environment, source)
|
self.upsert_environment(&environment, source)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Find other environments with the same parent folder
|
|
||||||
fn list_duplicate_folder_environments(&self, environment: &Environment) -> Vec<Environment> {
|
|
||||||
if environment.parent_model != "folder" {
|
|
||||||
return Vec::new();
|
|
||||||
}
|
|
||||||
|
|
||||||
self.list_environments_dangerous(&environment.workspace_id)
|
|
||||||
.unwrap_or_default()
|
|
||||||
.into_iter()
|
|
||||||
.filter(|e| {
|
|
||||||
e.id != environment.id
|
|
||||||
&& e.parent_model == "folder"
|
|
||||||
&& e.parent_id == environment.parent_id
|
|
||||||
})
|
|
||||||
.collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn upsert_environment(
|
pub fn upsert_environment(
|
||||||
&self,
|
&self,
|
||||||
environment: &Environment,
|
environment: &Environment,
|
||||||
@@ -154,43 +195,4 @@ impl<'a> ClientDb<'a> {
|
|||||||
source,
|
source,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn resolve_environments(
|
|
||||||
&self,
|
|
||||||
workspace_id: &str,
|
|
||||||
folder_id: Option<&str>,
|
|
||||||
active_environment_id: Option<&str>,
|
|
||||||
) -> Result<Vec<Environment>> {
|
|
||||||
let mut environments = Vec::new();
|
|
||||||
|
|
||||||
if let Some(folder_id) = folder_id {
|
|
||||||
let folder = self.get_folder(folder_id)?;
|
|
||||||
|
|
||||||
// Add current folder's environment
|
|
||||||
if let Some(e) = self.get_environment_by_folder_id(folder_id)? {
|
|
||||||
environments.push(e);
|
|
||||||
};
|
|
||||||
|
|
||||||
// Recurse up
|
|
||||||
let ancestors = self.resolve_environments(
|
|
||||||
workspace_id,
|
|
||||||
folder.folder_id.as_deref(),
|
|
||||||
active_environment_id,
|
|
||||||
)?;
|
|
||||||
environments.extend(ancestors);
|
|
||||||
} else {
|
|
||||||
// Add active and base environments
|
|
||||||
if let Some(id) = active_environment_id {
|
|
||||||
if let Ok(e) = self.get_environment(&id) {
|
|
||||||
// Add active sub environment
|
|
||||||
environments.push(e);
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
// Add the base environment
|
|
||||||
environments.push(self.get_base_environment(workspace_id)?);
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(environments)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
use super::{conflict_free_name, merge_headers};
|
use super::{conflict_free_name, merge_headers};
|
||||||
use crate::client_db::ClientDb;
|
use crate::client_db::{ClientDb, WriteDb};
|
||||||
use crate::connection_or_tx::ConnectionOrTx;
|
use crate::connection_or_tx::ConnectionOrTx;
|
||||||
use crate::error::Result;
|
use crate::error::Result;
|
||||||
use crate::models::{
|
use crate::models::{
|
||||||
@@ -20,99 +20,6 @@ impl<'a> ClientDb<'a> {
|
|||||||
self.find_many(FolderIden::WorkspaceId, workspace_id, None)
|
self.find_many(FolderIden::WorkspaceId, workspace_id, None)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn delete_folder(&self, folder: &Folder, source: &UpdateSource) -> Result<Folder> {
|
|
||||||
match self.conn() {
|
|
||||||
ConnectionOrTx::Connection(_) => {}
|
|
||||||
ConnectionOrTx::Transaction(_) => {}
|
|
||||||
}
|
|
||||||
|
|
||||||
let fid = &folder.id;
|
|
||||||
for m in self.find_many::<HttpRequest>(HttpRequestIden::FolderId, fid, None)? {
|
|
||||||
self.delete_http_request(&m, source)?;
|
|
||||||
}
|
|
||||||
|
|
||||||
for m in self.find_many::<GrpcRequest>(GrpcRequestIden::FolderId, fid, None)? {
|
|
||||||
self.delete_grpc_request(&m, source)?;
|
|
||||||
}
|
|
||||||
|
|
||||||
for m in self.find_many::<WebsocketRequest>(WebsocketRequestIden::FolderId, fid, None)? {
|
|
||||||
self.delete_websocket_request(&m, source)?;
|
|
||||||
}
|
|
||||||
|
|
||||||
for e in self.find_many(EnvironmentIden::ParentId, fid, None)? {
|
|
||||||
self.delete_environment(&e, source)?;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Recurse down into child folders
|
|
||||||
for folder in self.find_many::<Folder>(FolderIden::FolderId, fid, None)? {
|
|
||||||
self.delete_folder(&folder, source)?;
|
|
||||||
}
|
|
||||||
|
|
||||||
self.delete(folder, source)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn delete_folder_by_id(&self, id: &str, source: &UpdateSource) -> Result<Folder> {
|
|
||||||
let folder = self.get_folder(id)?;
|
|
||||||
self.delete_folder(&folder, source)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn upsert_folder(&self, folder: &Folder, source: &UpdateSource) -> Result<Folder> {
|
|
||||||
self.upsert(folder, source)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn duplicate_folder(&self, src_folder: &Folder, source: &UpdateSource) -> Result<Folder> {
|
|
||||||
let fid = &src_folder.id;
|
|
||||||
|
|
||||||
let mut folder = Folder {
|
|
||||||
id: "".into(),
|
|
||||||
sort_priority: src_folder.sort_priority + 0.001,
|
|
||||||
..src_folder.clone()
|
|
||||||
};
|
|
||||||
let sibling_names = self
|
|
||||||
.list_folders(&folder.workspace_id)?
|
|
||||||
.into_iter()
|
|
||||||
.filter(|f| f.folder_id == folder.folder_id)
|
|
||||||
.map(|f| f.name)
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
folder.name = conflict_free_name(&folder.name, &sibling_names);
|
|
||||||
let new_folder = self.upsert_folder(&folder, source)?;
|
|
||||||
|
|
||||||
for m in self.find_many::<HttpRequest>(HttpRequestIden::FolderId, fid, None)? {
|
|
||||||
self.upsert_http_request(
|
|
||||||
&HttpRequest { id: "".into(), folder_id: Some(new_folder.id.clone()), ..m },
|
|
||||||
source,
|
|
||||||
)?;
|
|
||||||
}
|
|
||||||
|
|
||||||
for m in self.find_many::<WebsocketRequest>(WebsocketRequestIden::FolderId, fid, None)? {
|
|
||||||
self.upsert_websocket_request(
|
|
||||||
&WebsocketRequest { id: "".into(), folder_id: Some(new_folder.id.clone()), ..m },
|
|
||||||
source,
|
|
||||||
)?;
|
|
||||||
}
|
|
||||||
|
|
||||||
for m in self.find_many::<GrpcRequest>(GrpcRequestIden::FolderId, fid, None)? {
|
|
||||||
self.upsert_grpc_request(
|
|
||||||
&GrpcRequest { id: "".into(), folder_id: Some(new_folder.id.clone()), ..m },
|
|
||||||
source,
|
|
||||||
)?;
|
|
||||||
}
|
|
||||||
|
|
||||||
for m in self.find_many::<Environment>(EnvironmentIden::ParentId, fid, None)? {
|
|
||||||
self.upsert_environment(
|
|
||||||
&Environment { id: "".into(), parent_id: Some(new_folder.id.clone()), ..m },
|
|
||||||
source,
|
|
||||||
)?;
|
|
||||||
}
|
|
||||||
|
|
||||||
for m in self.find_many::<Folder>(FolderIden::FolderId, fid, None)? {
|
|
||||||
// Recurse down
|
|
||||||
self.duplicate_folder(&Folder { folder_id: Some(new_folder.id.clone()), ..m }, source)?;
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(new_folder)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn resolve_auth_for_folder(
|
pub fn resolve_auth_for_folder(
|
||||||
&self,
|
&self,
|
||||||
folder: &Folder,
|
folder: &Folder,
|
||||||
@@ -219,3 +126,98 @@ impl<'a> ClientDb<'a> {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl<'a> WriteDb<'a> {
|
||||||
|
pub fn delete_folder(&self, folder: &Folder, source: &UpdateSource) -> Result<Folder> {
|
||||||
|
match self.conn() {
|
||||||
|
ConnectionOrTx::Connection(_) => {}
|
||||||
|
ConnectionOrTx::Transaction(_) => {}
|
||||||
|
}
|
||||||
|
|
||||||
|
let fid = &folder.id;
|
||||||
|
for m in self.find_many::<HttpRequest>(HttpRequestIden::FolderId, fid, None)? {
|
||||||
|
self.delete_http_request(&m, source)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
for m in self.find_many::<GrpcRequest>(GrpcRequestIden::FolderId, fid, None)? {
|
||||||
|
self.delete_grpc_request(&m, source)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
for m in self.find_many::<WebsocketRequest>(WebsocketRequestIden::FolderId, fid, None)? {
|
||||||
|
self.delete_websocket_request(&m, source)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
for e in self.find_many(EnvironmentIden::ParentId, fid, None)? {
|
||||||
|
self.delete_environment(&e, source)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Recurse down into child folders
|
||||||
|
for folder in self.find_many::<Folder>(FolderIden::FolderId, fid, None)? {
|
||||||
|
self.delete_folder(&folder, source)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
self.delete(folder, source)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn delete_folder_by_id(&self, id: &str, source: &UpdateSource) -> Result<Folder> {
|
||||||
|
let folder = self.get_folder(id)?;
|
||||||
|
self.delete_folder(&folder, source)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn upsert_folder(&self, folder: &Folder, source: &UpdateSource) -> Result<Folder> {
|
||||||
|
self.upsert(folder, source)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn duplicate_folder(&self, src_folder: &Folder, source: &UpdateSource) -> Result<Folder> {
|
||||||
|
let fid = &src_folder.id;
|
||||||
|
|
||||||
|
let mut folder = Folder {
|
||||||
|
id: "".into(),
|
||||||
|
sort_priority: src_folder.sort_priority + 0.001,
|
||||||
|
..src_folder.clone()
|
||||||
|
};
|
||||||
|
let sibling_names = self
|
||||||
|
.list_folders(&folder.workspace_id)?
|
||||||
|
.into_iter()
|
||||||
|
.filter(|f| f.folder_id == folder.folder_id)
|
||||||
|
.map(|f| f.name)
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
folder.name = conflict_free_name(&folder.name, &sibling_names);
|
||||||
|
let new_folder = self.upsert_folder(&folder, source)?;
|
||||||
|
|
||||||
|
for m in self.find_many::<HttpRequest>(HttpRequestIden::FolderId, fid, None)? {
|
||||||
|
self.upsert_http_request(
|
||||||
|
&HttpRequest { id: "".into(), folder_id: Some(new_folder.id.clone()), ..m },
|
||||||
|
source,
|
||||||
|
)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
for m in self.find_many::<WebsocketRequest>(WebsocketRequestIden::FolderId, fid, None)? {
|
||||||
|
self.upsert_websocket_request(
|
||||||
|
&WebsocketRequest { id: "".into(), folder_id: Some(new_folder.id.clone()), ..m },
|
||||||
|
source,
|
||||||
|
)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
for m in self.find_many::<GrpcRequest>(GrpcRequestIden::FolderId, fid, None)? {
|
||||||
|
self.upsert_grpc_request(
|
||||||
|
&GrpcRequest { id: "".into(), folder_id: Some(new_folder.id.clone()), ..m },
|
||||||
|
source,
|
||||||
|
)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
for m in self.find_many::<Environment>(EnvironmentIden::ParentId, fid, None)? {
|
||||||
|
self.upsert_environment(
|
||||||
|
&Environment { id: "".into(), parent_id: Some(new_folder.id.clone()), ..m },
|
||||||
|
source,
|
||||||
|
)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
for m in self.find_many::<Folder>(FolderIden::FolderId, fid, None)? {
|
||||||
|
// Recurse down
|
||||||
|
self.duplicate_folder(&Folder { folder_id: Some(new_folder.id.clone()), ..m }, source)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(new_folder)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
use crate::client_db::ClientDb;
|
use crate::client_db::{ClientDb, WriteDb};
|
||||||
use crate::error::Result;
|
use crate::error::Result;
|
||||||
use crate::models::{GraphQlIntrospection, GraphQlIntrospectionIden};
|
use crate::models::{GraphQlIntrospection, GraphQlIntrospectionIden};
|
||||||
use crate::util::UpdateSource;
|
use crate::util::UpdateSource;
|
||||||
@@ -11,7 +11,9 @@ impl<'a> ClientDb<'a> {
|
|||||||
pub fn get_graphql_introspection(&self, request_id: &str) -> Option<GraphQlIntrospection> {
|
pub fn get_graphql_introspection(&self, request_id: &str) -> Option<GraphQlIntrospection> {
|
||||||
self.find_optional(GraphQlIntrospectionIden::RequestId, request_id)
|
self.find_optional(GraphQlIntrospectionIden::RequestId, request_id)
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> WriteDb<'a> {
|
||||||
pub fn upsert_graphql_introspection(
|
pub fn upsert_graphql_introspection(
|
||||||
&self,
|
&self,
|
||||||
workspace_id: &str,
|
workspace_id: &str,
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
use crate::client_db::ClientDb;
|
use crate::client_db::{ClientDb, WriteDb};
|
||||||
use crate::error::Result;
|
use crate::error::Result;
|
||||||
use crate::models::{GrpcConnection, GrpcConnectionIden, GrpcConnectionState};
|
use crate::models::{GrpcConnection, GrpcConnectionIden, GrpcConnectionState};
|
||||||
use crate::queries::MAX_HISTORY_ITEMS;
|
use crate::queries::MAX_HISTORY_ITEMS;
|
||||||
@@ -13,6 +13,20 @@ impl<'a> ClientDb<'a> {
|
|||||||
self.find_one(GrpcConnectionIden::Id, id)
|
self.find_one(GrpcConnectionIden::Id, id)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn list_grpc_connections_for_request(
|
||||||
|
&self,
|
||||||
|
request_id: &str,
|
||||||
|
limit: Option<u64>,
|
||||||
|
) -> Result<Vec<GrpcConnection>> {
|
||||||
|
self.find_many(GrpcConnectionIden::RequestId, request_id, limit)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn list_grpc_connections(&self, workspace_id: &str) -> Result<Vec<GrpcConnection>> {
|
||||||
|
self.find_many(GrpcConnectionIden::WorkspaceId, workspace_id, None)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> WriteDb<'a> {
|
||||||
pub fn delete_all_grpc_connections_for_request(
|
pub fn delete_all_grpc_connections_for_request(
|
||||||
&self,
|
&self,
|
||||||
request_id: &str,
|
request_id: &str,
|
||||||
@@ -53,18 +67,6 @@ impl<'a> ClientDb<'a> {
|
|||||||
self.delete_grpc_connection(&grpc_connection, source)
|
self.delete_grpc_connection(&grpc_connection, source)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn list_grpc_connections_for_request(
|
|
||||||
&self,
|
|
||||||
request_id: &str,
|
|
||||||
limit: Option<u64>,
|
|
||||||
) -> Result<Vec<GrpcConnection>> {
|
|
||||||
self.find_many(GrpcConnectionIden::RequestId, request_id, limit)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn list_grpc_connections(&self, workspace_id: &str) -> Result<Vec<GrpcConnection>> {
|
|
||||||
self.find_many(GrpcConnectionIden::WorkspaceId, workspace_id, None)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn cancel_pending_grpc_connections(&self) -> Result<()> {
|
pub fn cancel_pending_grpc_connections(&self) -> Result<()> {
|
||||||
let closed = serde_json::to_value(&GrpcConnectionState::Closed)?;
|
let closed = serde_json::to_value(&GrpcConnectionState::Closed)?;
|
||||||
let (sql, params) = Query::update()
|
let (sql, params) = Query::update()
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
use crate::client_db::ClientDb;
|
use crate::client_db::{ClientDb, WriteDb};
|
||||||
use crate::error::Result;
|
use crate::error::Result;
|
||||||
use crate::models::{GrpcEvent, GrpcEventIden};
|
use crate::models::{GrpcEvent, GrpcEventIden};
|
||||||
use crate::util::UpdateSource;
|
use crate::util::UpdateSource;
|
||||||
@@ -11,7 +11,9 @@ impl<'a> ClientDb<'a> {
|
|||||||
pub fn list_grpc_events(&self, connection_id: &str) -> Result<Vec<GrpcEvent>> {
|
pub fn list_grpc_events(&self, connection_id: &str) -> Result<Vec<GrpcEvent>> {
|
||||||
self.find_many(GrpcEventIden::ConnectionId, connection_id, None)
|
self.find_many(GrpcEventIden::ConnectionId, connection_id, None)
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> WriteDb<'a> {
|
||||||
pub fn upsert_grpc_event(
|
pub fn upsert_grpc_event(
|
||||||
&self,
|
&self,
|
||||||
grpc_event: &GrpcEvent,
|
grpc_event: &GrpcEvent,
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
use super::{conflict_free_name, merge_headers};
|
use super::{conflict_free_name, merge_headers};
|
||||||
use crate::client_db::ClientDb;
|
use crate::client_db::{ClientDb, WriteDb};
|
||||||
use crate::error::Result;
|
use crate::error::Result;
|
||||||
use crate::models::{
|
use crate::models::{
|
||||||
AnyModel, Folder, FolderIden, GrpcRequest, GrpcRequestIden, HttpRequestHeader,
|
AnyModel, Folder, FolderIden, GrpcRequest, GrpcRequestIden, HttpRequestHeader,
|
||||||
@@ -32,50 +32,6 @@ impl<'a> ClientDb<'a> {
|
|||||||
Ok(children)
|
Ok(children)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn delete_grpc_request(
|
|
||||||
&self,
|
|
||||||
m: &GrpcRequest,
|
|
||||||
source: &UpdateSource,
|
|
||||||
) -> Result<GrpcRequest> {
|
|
||||||
self.delete_all_grpc_connections_for_request(m.id.as_str(), source)?;
|
|
||||||
self.delete(m, source)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn delete_grpc_request_by_id(
|
|
||||||
&self,
|
|
||||||
id: &str,
|
|
||||||
source: &UpdateSource,
|
|
||||||
) -> Result<GrpcRequest> {
|
|
||||||
let request = self.get_grpc_request(id)?;
|
|
||||||
self.delete_grpc_request(&request, source)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn duplicate_grpc_request(
|
|
||||||
&self,
|
|
||||||
grpc_request: &GrpcRequest,
|
|
||||||
source: &UpdateSource,
|
|
||||||
) -> Result<GrpcRequest> {
|
|
||||||
let mut request = grpc_request.clone();
|
|
||||||
request.id = "".to_string();
|
|
||||||
request.sort_priority = request.sort_priority + 0.001;
|
|
||||||
let sibling_names = self
|
|
||||||
.list_grpc_requests(&request.workspace_id)?
|
|
||||||
.into_iter()
|
|
||||||
.filter(|m| m.folder_id == request.folder_id)
|
|
||||||
.map(|m| m.name)
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
request.name = conflict_free_name(&request.name, &sibling_names);
|
|
||||||
self.upsert(&request, source)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn upsert_grpc_request(
|
|
||||||
&self,
|
|
||||||
grpc_request: &GrpcRequest,
|
|
||||||
source: &UpdateSource,
|
|
||||||
) -> Result<GrpcRequest> {
|
|
||||||
self.upsert(grpc_request, source)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn resolve_auth_for_grpc_request(
|
pub fn resolve_auth_for_grpc_request(
|
||||||
&self,
|
&self,
|
||||||
grpc_request: &GrpcRequest,
|
grpc_request: &GrpcRequest,
|
||||||
@@ -146,3 +102,49 @@ impl<'a> ClientDb<'a> {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl<'a> WriteDb<'a> {
|
||||||
|
pub fn delete_grpc_request(
|
||||||
|
&self,
|
||||||
|
m: &GrpcRequest,
|
||||||
|
source: &UpdateSource,
|
||||||
|
) -> Result<GrpcRequest> {
|
||||||
|
self.delete_all_grpc_connections_for_request(m.id.as_str(), source)?;
|
||||||
|
self.delete(m, source)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn delete_grpc_request_by_id(
|
||||||
|
&self,
|
||||||
|
id: &str,
|
||||||
|
source: &UpdateSource,
|
||||||
|
) -> Result<GrpcRequest> {
|
||||||
|
let request = self.get_grpc_request(id)?;
|
||||||
|
self.delete_grpc_request(&request, source)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn duplicate_grpc_request(
|
||||||
|
&self,
|
||||||
|
grpc_request: &GrpcRequest,
|
||||||
|
source: &UpdateSource,
|
||||||
|
) -> Result<GrpcRequest> {
|
||||||
|
let mut request = grpc_request.clone();
|
||||||
|
request.id = "".to_string();
|
||||||
|
request.sort_priority = request.sort_priority + 0.001;
|
||||||
|
let sibling_names = self
|
||||||
|
.list_grpc_requests(&request.workspace_id)?
|
||||||
|
.into_iter()
|
||||||
|
.filter(|m| m.folder_id == request.folder_id)
|
||||||
|
.map(|m| m.name)
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
request.name = conflict_free_name(&request.name, &sibling_names);
|
||||||
|
self.upsert(&request, source)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn upsert_grpc_request(
|
||||||
|
&self,
|
||||||
|
grpc_request: &GrpcRequest,
|
||||||
|
source: &UpdateSource,
|
||||||
|
) -> Result<GrpcRequest> {
|
||||||
|
self.upsert(grpc_request, source)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
use super::{conflict_free_name, merge_headers};
|
use super::{conflict_free_name, merge_headers};
|
||||||
use crate::client_db::ClientDb;
|
use crate::client_db::{ClientDb, WriteDb};
|
||||||
use crate::error::Result;
|
use crate::error::Result;
|
||||||
use crate::models::{
|
use crate::models::{
|
||||||
AnyModel, Folder, FolderIden, HttpRequest, HttpRequestHeader, HttpRequestIden,
|
AnyModel, Folder, FolderIden, HttpRequest, HttpRequestHeader, HttpRequestIden,
|
||||||
@@ -18,50 +18,6 @@ impl<'a> ClientDb<'a> {
|
|||||||
self.find_many(HttpRequestIden::WorkspaceId, workspace_id, None)
|
self.find_many(HttpRequestIden::WorkspaceId, workspace_id, None)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn delete_http_request(
|
|
||||||
&self,
|
|
||||||
m: &HttpRequest,
|
|
||||||
source: &UpdateSource,
|
|
||||||
) -> Result<HttpRequest> {
|
|
||||||
self.delete_all_http_responses_for_request(m.id.as_str(), source)?;
|
|
||||||
self.delete(m, source)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn delete_http_request_by_id(
|
|
||||||
&self,
|
|
||||||
id: &str,
|
|
||||||
source: &UpdateSource,
|
|
||||||
) -> Result<HttpRequest> {
|
|
||||||
let http_request = self.get_http_request(id)?;
|
|
||||||
self.delete_http_request(&http_request, source)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn duplicate_http_request(
|
|
||||||
&self,
|
|
||||||
http_request: &HttpRequest,
|
|
||||||
source: &UpdateSource,
|
|
||||||
) -> Result<HttpRequest> {
|
|
||||||
let mut http_request = http_request.clone();
|
|
||||||
http_request.id = "".to_string();
|
|
||||||
http_request.sort_priority = http_request.sort_priority + 0.001;
|
|
||||||
let sibling_names = self
|
|
||||||
.list_http_requests(&http_request.workspace_id)?
|
|
||||||
.into_iter()
|
|
||||||
.filter(|m| m.folder_id == http_request.folder_id)
|
|
||||||
.map(|m| m.name)
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
http_request.name = conflict_free_name(&http_request.name, &sibling_names);
|
|
||||||
self.upsert(&http_request, source)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn upsert_http_request(
|
|
||||||
&self,
|
|
||||||
http_request: &HttpRequest,
|
|
||||||
source: &UpdateSource,
|
|
||||||
) -> Result<HttpRequest> {
|
|
||||||
self.upsert(http_request, source)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn resolve_auth_for_http_request(
|
pub fn resolve_auth_for_http_request(
|
||||||
&self,
|
&self,
|
||||||
http_request: &HttpRequest,
|
http_request: &HttpRequest,
|
||||||
@@ -179,6 +135,52 @@ impl<'a> ClientDb<'a> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl<'a> WriteDb<'a> {
|
||||||
|
pub fn delete_http_request(
|
||||||
|
&self,
|
||||||
|
m: &HttpRequest,
|
||||||
|
source: &UpdateSource,
|
||||||
|
) -> Result<HttpRequest> {
|
||||||
|
self.delete_all_http_responses_for_request(m.id.as_str(), source)?;
|
||||||
|
self.delete(m, source)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn delete_http_request_by_id(
|
||||||
|
&self,
|
||||||
|
id: &str,
|
||||||
|
source: &UpdateSource,
|
||||||
|
) -> Result<HttpRequest> {
|
||||||
|
let http_request = self.get_http_request(id)?;
|
||||||
|
self.delete_http_request(&http_request, source)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn duplicate_http_request(
|
||||||
|
&self,
|
||||||
|
http_request: &HttpRequest,
|
||||||
|
source: &UpdateSource,
|
||||||
|
) -> Result<HttpRequest> {
|
||||||
|
let mut http_request = http_request.clone();
|
||||||
|
http_request.id = "".to_string();
|
||||||
|
http_request.sort_priority = http_request.sort_priority + 0.001;
|
||||||
|
let sibling_names = self
|
||||||
|
.list_http_requests(&http_request.workspace_id)?
|
||||||
|
.into_iter()
|
||||||
|
.filter(|m| m.folder_id == http_request.folder_id)
|
||||||
|
.map(|m| m.name)
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
http_request.name = conflict_free_name(&http_request.name, &sibling_names);
|
||||||
|
self.upsert(&http_request, source)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn upsert_http_request(
|
||||||
|
&self,
|
||||||
|
http_request: &HttpRequest,
|
||||||
|
source: &UpdateSource,
|
||||||
|
) -> Result<HttpRequest> {
|
||||||
|
self.upsert(http_request, source)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use crate::init_in_memory;
|
use crate::init_in_memory;
|
||||||
@@ -225,72 +227,83 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn http_version_resolves_through_the_inheritance_chain() {
|
fn http_version_resolves_through_the_inheritance_chain() {
|
||||||
let (query_manager, _blob_manager, _rx) = init_in_memory().expect("Failed to init DB");
|
let (query_manager, _blob_manager, _rx) = init_in_memory().expect("Failed to init DB");
|
||||||
let db = query_manager.connect();
|
let source = &UpdateSource::Background;
|
||||||
|
|
||||||
let workspace = db
|
let (folder, request) = query_manager
|
||||||
.upsert_workspace(
|
.with_tx(|db| {
|
||||||
&Workspace {
|
let workspace = db.upsert_workspace(
|
||||||
name: "Test".to_string(),
|
&Workspace {
|
||||||
setting_http_version: HttpVersion::Http2,
|
name: "Test".to_string(),
|
||||||
..Default::default()
|
setting_http_version: HttpVersion::Http2,
|
||||||
},
|
..Default::default()
|
||||||
&UpdateSource::Background,
|
},
|
||||||
)
|
source,
|
||||||
.expect("Failed to upsert workspace");
|
)?;
|
||||||
|
let folder = db.upsert_folder(
|
||||||
let folder = db
|
&Folder { workspace_id: workspace.id.clone(), ..Default::default() },
|
||||||
.upsert_folder(
|
source,
|
||||||
&Folder { workspace_id: workspace.id.clone(), ..Default::default() },
|
)?;
|
||||||
&UpdateSource::Background,
|
let request = db.upsert_http_request(
|
||||||
)
|
&HttpRequest {
|
||||||
.expect("Failed to upsert folder");
|
workspace_id: workspace.id.clone(),
|
||||||
|
folder_id: Some(folder.id.clone()),
|
||||||
let request = db
|
..Default::default()
|
||||||
.upsert_http_request(
|
},
|
||||||
&HttpRequest {
|
source,
|
||||||
workspace_id: workspace.id.clone(),
|
)?;
|
||||||
folder_id: Some(folder.id.clone()),
|
Ok::<_, crate::error::Error>((folder, request))
|
||||||
..Default::default()
|
})
|
||||||
},
|
.expect("Failed to seed");
|
||||||
&UpdateSource::Background,
|
|
||||||
)
|
|
||||||
.expect("Failed to upsert request");
|
|
||||||
|
|
||||||
// No overrides, so the workspace base value applies
|
// No overrides, so the workspace base value applies
|
||||||
let resolved = db.resolve_settings_for_http_request(&request).expect("Failed to resolve");
|
let resolved = query_manager
|
||||||
|
.connect()
|
||||||
|
.resolve_settings_for_http_request(&request)
|
||||||
|
.expect("Failed to resolve");
|
||||||
assert_eq!(resolved.http_version.value, HttpVersion::Http2);
|
assert_eq!(resolved.http_version.value, HttpVersion::Http2);
|
||||||
assert_eq!(resolved.http_version.source_model, "workspace");
|
assert_eq!(resolved.http_version.source_model, "workspace");
|
||||||
|
|
||||||
// A folder override beats the workspace base
|
// A folder override beats the workspace base
|
||||||
db.upsert_folder(
|
query_manager
|
||||||
&Folder {
|
.with_tx(|db| {
|
||||||
setting_http_version: InheritedHttpVersionSetting {
|
db.upsert_folder(
|
||||||
enabled: true,
|
&Folder {
|
||||||
value: HttpVersion::Http1,
|
setting_http_version: InheritedHttpVersionSetting {
|
||||||
},
|
enabled: true,
|
||||||
..folder
|
value: HttpVersion::Http1,
|
||||||
},
|
},
|
||||||
&UpdateSource::Background,
|
..folder
|
||||||
)
|
},
|
||||||
.expect("Failed to update folder");
|
source,
|
||||||
let resolved = db.resolve_settings_for_http_request(&request).expect("Failed to resolve");
|
)
|
||||||
|
})
|
||||||
|
.expect("Failed to update folder");
|
||||||
|
let resolved = query_manager
|
||||||
|
.connect()
|
||||||
|
.resolve_settings_for_http_request(&request)
|
||||||
|
.expect("Failed to resolve");
|
||||||
assert_eq!(resolved.http_version.value, HttpVersion::Http1);
|
assert_eq!(resolved.http_version.value, HttpVersion::Http1);
|
||||||
assert_eq!(resolved.http_version.source_model, "folder");
|
assert_eq!(resolved.http_version.source_model, "folder");
|
||||||
|
|
||||||
// A request override beats them both
|
// A request override beats them both
|
||||||
let request = db
|
let request = query_manager
|
||||||
.upsert_http_request(
|
.with_tx(|db| {
|
||||||
&HttpRequest {
|
db.upsert_http_request(
|
||||||
setting_http_version: InheritedHttpVersionSetting {
|
&HttpRequest {
|
||||||
enabled: true,
|
setting_http_version: InheritedHttpVersionSetting {
|
||||||
value: HttpVersion::Auto,
|
enabled: true,
|
||||||
|
value: HttpVersion::Auto,
|
||||||
|
},
|
||||||
|
..request
|
||||||
},
|
},
|
||||||
..request
|
source,
|
||||||
},
|
)
|
||||||
&UpdateSource::Background,
|
})
|
||||||
)
|
|
||||||
.expect("Failed to update request");
|
.expect("Failed to update request");
|
||||||
let resolved = db.resolve_settings_for_http_request(&request).expect("Failed to resolve");
|
let resolved = query_manager
|
||||||
|
.connect()
|
||||||
|
.resolve_settings_for_http_request(&request)
|
||||||
|
.expect("Failed to resolve");
|
||||||
assert_eq!(resolved.http_version.value, HttpVersion::Auto);
|
assert_eq!(resolved.http_version.value, HttpVersion::Auto);
|
||||||
assert_eq!(resolved.http_version.source_model, "http_request");
|
assert_eq!(resolved.http_version.source_model, "http_request");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
use crate::client_db::ClientDb;
|
use crate::client_db::{ClientDb, WriteDb};
|
||||||
use crate::error::Result;
|
use crate::error::Result;
|
||||||
use crate::models::{HttpResponseEvent, HttpResponseEventIden};
|
use crate::models::{HttpResponseEvent, HttpResponseEventIden};
|
||||||
use crate::util::UpdateSource;
|
use crate::util::UpdateSource;
|
||||||
@@ -7,7 +7,9 @@ impl<'a> ClientDb<'a> {
|
|||||||
pub fn list_http_response_events(&self, response_id: &str) -> Result<Vec<HttpResponseEvent>> {
|
pub fn list_http_response_events(&self, response_id: &str) -> Result<Vec<HttpResponseEvent>> {
|
||||||
self.find_many(HttpResponseEventIden::ResponseId, response_id, None)
|
self.find_many(HttpResponseEventIden::ResponseId, response_id, None)
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> WriteDb<'a> {
|
||||||
pub fn upsert_http_response_event(
|
pub fn upsert_http_response_event(
|
||||||
&self,
|
&self,
|
||||||
http_response_event: &HttpResponseEvent,
|
http_response_event: &HttpResponseEvent,
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
use crate::blob_manager::BlobManager;
|
use crate::blob_manager::BlobManager;
|
||||||
use crate::client_db::ClientDb;
|
use crate::client_db::{ClientDb, WriteDb};
|
||||||
use crate::error::Result;
|
use crate::error::Result;
|
||||||
use crate::models::{HttpResponse, HttpResponseIden, HttpResponseState};
|
use crate::models::{HttpResponse, HttpResponseIden, HttpResponseState};
|
||||||
use crate::queries::MAX_HISTORY_ITEMS;
|
use crate::queries::MAX_HISTORY_ITEMS;
|
||||||
@@ -31,20 +31,6 @@ impl<'a> ClientDb<'a> {
|
|||||||
self.find_many(HttpResponseIden::WorkspaceId, workspace_id, limit)
|
self.find_many(HttpResponseIden::WorkspaceId, workspace_id, limit)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the number of responses deleted.
|
|
||||||
pub fn delete_all_http_responses_for_request(
|
|
||||||
&self,
|
|
||||||
request_id: &str,
|
|
||||||
source: &UpdateSource,
|
|
||||||
) -> Result<usize> {
|
|
||||||
let responses = self.list_http_responses_for_request(request_id, None)?;
|
|
||||||
let count = responses.len();
|
|
||||||
for m in responses {
|
|
||||||
self.delete(&m, source)?;
|
|
||||||
}
|
|
||||||
Ok(count)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Delete blob-stored response bodies whose owning HTTP response row no
|
/// Delete blob-stored response bodies whose owning HTTP response row no
|
||||||
/// longer exists. Blob ids are keyed by the response that owns them —
|
/// longer exists. Blob ids are keyed by the response that owns them —
|
||||||
/// "{response_id}" for a response body, "{response_id}.request" for the
|
/// "{response_id}" for a response body, "{response_id}.request" for the
|
||||||
@@ -55,19 +41,24 @@ impl<'a> ClientDb<'a> {
|
|||||||
///
|
///
|
||||||
/// Returns the number of orphaned bodies deleted.
|
/// Returns the number of orphaned bodies deleted.
|
||||||
pub fn delete_orphaned_response_body_blobs(&self, blobs: &BlobManager) -> Result<usize> {
|
pub fn delete_orphaned_response_body_blobs(&self, blobs: &BlobManager) -> Result<usize> {
|
||||||
let mut deleted = 0;
|
let orphaned = blobs
|
||||||
|
.connect()
|
||||||
|
.list_body_ids()?
|
||||||
|
.into_iter()
|
||||||
|
.filter(|body_id| {
|
||||||
|
let response_id = body_id.split('.').next().unwrap_or_default();
|
||||||
|
self.find_optional::<HttpResponse>(HttpResponseIden::Id, response_id).is_none()
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
|
||||||
let blob_ctx = blobs.connect();
|
blobs.with_tx(|b| {
|
||||||
for body_id in blob_ctx.list_body_ids()? {
|
for body_id in &orphaned {
|
||||||
let response_id = body_id.split('.').next().unwrap_or_default();
|
b.delete_chunks(body_id)?;
|
||||||
if self.find_optional::<HttpResponse>(HttpResponseIden::Id, response_id).is_some() {
|
|
||||||
continue;
|
|
||||||
}
|
}
|
||||||
blob_ctx.delete_chunks(&body_id)?;
|
Ok::<_, crate::error::Error>(())
|
||||||
deleted += 1;
|
})?;
|
||||||
}
|
|
||||||
|
|
||||||
Ok(deleted)
|
Ok(orphaned.len())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Delete response body data (blob chunks and body files) whose owning HTTP
|
/// Delete response body data (blob chunks and body files) whose owning HTTP
|
||||||
@@ -96,8 +87,7 @@ impl<'a> ClientDb<'a> {
|
|||||||
let Some(response_id) = path.file_name().and_then(|n| n.to_str()) else {
|
let Some(response_id) = path.file_name().and_then(|n| n.to_str()) else {
|
||||||
continue;
|
continue;
|
||||||
};
|
};
|
||||||
if self.find_optional::<HttpResponse>(HttpResponseIden::Id, response_id).is_some()
|
if self.find_optional::<HttpResponse>(HttpResponseIden::Id, response_id).is_some() {
|
||||||
{
|
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if fs::remove_file(&path).is_ok() {
|
if fs::remove_file(&path).is_ok() {
|
||||||
@@ -108,6 +98,22 @@ impl<'a> ClientDb<'a> {
|
|||||||
|
|
||||||
Ok(deleted)
|
Ok(deleted)
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> WriteDb<'a> {
|
||||||
|
/// Returns the number of responses deleted.
|
||||||
|
pub fn delete_all_http_responses_for_request(
|
||||||
|
&self,
|
||||||
|
request_id: &str,
|
||||||
|
source: &UpdateSource,
|
||||||
|
) -> Result<usize> {
|
||||||
|
let responses = self.list_http_responses_for_request(request_id, None)?;
|
||||||
|
let count = responses.len();
|
||||||
|
for m in responses {
|
||||||
|
self.delete(&m, source)?;
|
||||||
|
}
|
||||||
|
Ok(count)
|
||||||
|
}
|
||||||
|
|
||||||
/// Returns the number of responses deleted.
|
/// Returns the number of responses deleted.
|
||||||
pub fn delete_all_http_responses_for_workspace(
|
pub fn delete_all_http_responses_for_workspace(
|
||||||
@@ -138,9 +144,8 @@ impl<'a> ClientDb<'a> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Delete request body blobs (pattern: {response_id}.request)
|
// Delete request body blobs (pattern: {response_id}.request)
|
||||||
let blob_ctx = blob_manager.connect();
|
|
||||||
let body_id = format!("{}.request", http_response.id);
|
let body_id = format!("{}.request", http_response.id);
|
||||||
if let Err(e) = blob_ctx.delete_chunks(&body_id) {
|
if let Err(e) = blob_manager.with_tx(|b| b.delete_chunks(&body_id)) {
|
||||||
error!("Failed to delete request body blobs: {}", e);
|
error!("Failed to delete request body blobs: {}", e);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -187,36 +192,50 @@ impl<'a> ClientDb<'a> {
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use crate::blob_manager::{BlobManager, BodyChunk};
|
use crate::blob_manager::{BlobManager, BodyChunk};
|
||||||
use crate::client_db::ClientDb;
|
use crate::error::Error;
|
||||||
use crate::init_in_memory;
|
use crate::init_in_memory;
|
||||||
use crate::models::{HttpRequest, HttpResponse, Workspace};
|
use crate::models::{HttpRequest, HttpResponse, Workspace};
|
||||||
|
use crate::query_manager::QueryManager;
|
||||||
use crate::util::UpdateSource;
|
use crate::util::UpdateSource;
|
||||||
|
|
||||||
/// A workspace, a request, and one response that still exists.
|
/// A workspace, a request, and one response that still exists.
|
||||||
fn seed_live_response(db: &ClientDb, blob_manager: &BlobManager) -> HttpResponse {
|
fn seed_live_response(
|
||||||
|
query_manager: &QueryManager,
|
||||||
|
blob_manager: &BlobManager,
|
||||||
|
) -> HttpResponse {
|
||||||
let source = &UpdateSource::Background;
|
let source = &UpdateSource::Background;
|
||||||
let workspace = db
|
query_manager
|
||||||
.upsert_workspace(
|
.with_tx(|db| {
|
||||||
&Workspace { name: "GC Test".to_string(), ..Default::default() },
|
let workspace = db.upsert_workspace(
|
||||||
source,
|
&Workspace { name: "GC Test".to_string(), ..Default::default() },
|
||||||
)
|
source,
|
||||||
.expect("Failed to upsert workspace");
|
)?;
|
||||||
let request = db
|
let request = db.upsert_http_request(
|
||||||
.upsert_http_request(
|
&HttpRequest { workspace_id: workspace.id.clone(), ..Default::default() },
|
||||||
&HttpRequest { workspace_id: workspace.id.clone(), ..Default::default() },
|
source,
|
||||||
source,
|
)?;
|
||||||
)
|
db.upsert_http_response(
|
||||||
.expect("Failed to upsert request");
|
&HttpResponse {
|
||||||
db.upsert_http_response(
|
request_id: request.id.clone(),
|
||||||
&HttpResponse {
|
workspace_id: workspace.id.clone(),
|
||||||
request_id: request.id.clone(),
|
..Default::default()
|
||||||
workspace_id: workspace.id.clone(),
|
},
|
||||||
..Default::default()
|
source,
|
||||||
},
|
blob_manager,
|
||||||
source,
|
)
|
||||||
blob_manager,
|
})
|
||||||
)
|
.expect("Failed to seed response")
|
||||||
.expect("Failed to upsert response")
|
}
|
||||||
|
|
||||||
|
fn insert_bodies(blob_manager: &BlobManager, body_ids: &[&str]) {
|
||||||
|
blob_manager
|
||||||
|
.with_tx(|b| {
|
||||||
|
for id in body_ids {
|
||||||
|
b.insert_chunk(&BodyChunk::new(*id, 0, b"data".to_vec()))?;
|
||||||
|
}
|
||||||
|
Ok::<_, Error>(())
|
||||||
|
})
|
||||||
|
.expect("Failed to insert chunks");
|
||||||
}
|
}
|
||||||
|
|
||||||
/// What a browser host runs: no filesystem, so bodies exist only as blob
|
/// What a browser host runs: no filesystem, so bodies exist only as blob
|
||||||
@@ -224,23 +243,21 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn deletes_orphaned_response_body_blobs() {
|
fn deletes_orphaned_response_body_blobs() {
|
||||||
let (query_manager, blob_manager, _rx) = init_in_memory().expect("Failed to init DB");
|
let (query_manager, blob_manager, _rx) = init_in_memory().expect("Failed to init DB");
|
||||||
let db = query_manager.connect();
|
|
||||||
|
|
||||||
let live = seed_live_response(&db, &blob_manager);
|
let live = seed_live_response(&query_manager, &blob_manager);
|
||||||
let live_request_body_id = format!("{}.request", live.id);
|
let live_request_body_id = format!("{}.request", live.id);
|
||||||
{
|
insert_bodies(
|
||||||
// Scope the connection: the in-memory pool only has one, and the GC
|
&blob_manager,
|
||||||
// needs to take it
|
&[
|
||||||
let blob_ctx = blob_manager.connect();
|
&live.id,
|
||||||
blob_ctx.insert_chunk(&BodyChunk::new(&live.id, 0, b"live".to_vec())).unwrap();
|
&live_request_body_id,
|
||||||
blob_ctx
|
"rs_gone",
|
||||||
.insert_chunk(&BodyChunk::new(&live_request_body_id, 0, b"live".to_vec()))
|
"rs_gone.request",
|
||||||
.unwrap();
|
],
|
||||||
blob_ctx.insert_chunk(&BodyChunk::new("rs_gone", 0, b"dead".to_vec())).unwrap();
|
);
|
||||||
blob_ctx.insert_chunk(&BodyChunk::new("rs_gone.request", 0, b"dead".to_vec())).unwrap();
|
|
||||||
}
|
|
||||||
|
|
||||||
let deleted = db
|
let deleted = query_manager
|
||||||
|
.connect()
|
||||||
.delete_orphaned_response_body_blobs(&blob_manager)
|
.delete_orphaned_response_body_blobs(&blob_manager)
|
||||||
.expect("Failed to GC response body blobs");
|
.expect("Failed to GC response body blobs");
|
||||||
assert_eq!(deleted, 2);
|
assert_eq!(deleted, 2);
|
||||||
@@ -255,24 +272,18 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn deletes_orphaned_response_bodies() {
|
fn deletes_orphaned_response_bodies() {
|
||||||
let (query_manager, blob_manager, _rx) = init_in_memory().expect("Failed to init DB");
|
let (query_manager, blob_manager, _rx) = init_in_memory().expect("Failed to init DB");
|
||||||
let db = query_manager.connect();
|
|
||||||
|
|
||||||
let live = seed_live_response(&db, &blob_manager);
|
let live = seed_live_response(&query_manager, &blob_manager);
|
||||||
let live_body_id = format!("{}.request", live.id);
|
let live_body_id = format!("{}.request", live.id);
|
||||||
{
|
insert_bodies(&blob_manager, &[&live_body_id, "rs_gone.request"]);
|
||||||
// Scope the connection: the in-memory pool only has one, and the GC
|
|
||||||
// needs to take it
|
|
||||||
let blob_ctx = blob_manager.connect();
|
|
||||||
blob_ctx.insert_chunk(&BodyChunk::new(&live_body_id, 0, b"live".to_vec())).unwrap();
|
|
||||||
blob_ctx.insert_chunk(&BodyChunk::new("rs_gone.request", 0, b"dead".to_vec())).unwrap();
|
|
||||||
}
|
|
||||||
|
|
||||||
let dir = std::env::temp_dir().join(format!("yaak-blob-gc-test-{}", live.id));
|
let dir = std::env::temp_dir().join(format!("yaak-blob-gc-test-{}", live.id));
|
||||||
std::fs::create_dir_all(&dir).unwrap();
|
std::fs::create_dir_all(&dir).unwrap();
|
||||||
std::fs::write(dir.join(&live.id), b"live").unwrap();
|
std::fs::write(dir.join(&live.id), b"live").unwrap();
|
||||||
std::fs::write(dir.join("rs_gone"), b"dead").unwrap();
|
std::fs::write(dir.join("rs_gone"), b"dead").unwrap();
|
||||||
|
|
||||||
let deleted = db
|
let deleted = query_manager
|
||||||
|
.connect()
|
||||||
.delete_orphaned_response_bodies(&blob_manager, &dir)
|
.delete_orphaned_response_bodies(&blob_manager, &dir)
|
||||||
.expect("Failed to GC response bodies");
|
.expect("Failed to GC response bodies");
|
||||||
assert_eq!(deleted, 2);
|
assert_eq!(deleted, 2);
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
use crate::client_db::ClientDb;
|
use crate::client_db::{ClientDb, WriteDb};
|
||||||
use crate::error::Result;
|
use crate::error::Result;
|
||||||
use crate::models::{ImportSourceResource, ImportSourceResourceIden};
|
use crate::models::{ImportSourceResource, ImportSourceResourceIden};
|
||||||
use sea_query::ExprTrait;
|
use sea_query::ExprTrait;
|
||||||
@@ -20,7 +20,9 @@ impl<'a> ClientDb<'a> {
|
|||||||
let items = stmt.query_map(&*params.as_params(), |row| row.try_into())?;
|
let items = stmt.query_map(&*params.as_params(), |row| row.try_into())?;
|
||||||
Ok(items.filter_map(|v| v.ok()).collect())
|
Ok(items.filter_map(|v| v.ok()).collect())
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> WriteDb<'a> {
|
||||||
pub fn upsert_import_source_resource(
|
pub fn upsert_import_source_resource(
|
||||||
&self,
|
&self,
|
||||||
resource: &ImportSourceResource,
|
resource: &ImportSourceResource,
|
||||||
@@ -34,7 +36,7 @@ impl<'a> ClientDb<'a> {
|
|||||||
ImportSourceResourceIden::SourceKey,
|
ImportSourceResourceIden::SourceKey,
|
||||||
ImportSourceResourceIden::ModelType,
|
ImportSourceResourceIden::ModelType,
|
||||||
ImportSourceResourceIden::ModelId,
|
ImportSourceResourceIden::ModelId,
|
||||||
ImportSourceResourceIden::Snapshot,
|
ImportSourceResourceIden::ContentHash,
|
||||||
])
|
])
|
||||||
.values_panic([
|
.values_panic([
|
||||||
CurrentTimestamp.into(),
|
CurrentTimestamp.into(),
|
||||||
@@ -42,8 +44,8 @@ impl<'a> ClientDb<'a> {
|
|||||||
resource.import_source_id.as_str().into(),
|
resource.import_source_id.as_str().into(),
|
||||||
resource.source_key.as_str().into(),
|
resource.source_key.as_str().into(),
|
||||||
resource.model_type.as_str().into(),
|
resource.model_type.as_str().into(),
|
||||||
resource.model_id.as_str().into(),
|
resource.model_id.clone().into(),
|
||||||
resource.snapshot.as_str().into(),
|
resource.content_hash.clone().into(),
|
||||||
])
|
])
|
||||||
.on_conflict(
|
.on_conflict(
|
||||||
OnConflict::columns([
|
OnConflict::columns([
|
||||||
@@ -54,7 +56,7 @@ impl<'a> ClientDb<'a> {
|
|||||||
ImportSourceResourceIden::UpdatedAt,
|
ImportSourceResourceIden::UpdatedAt,
|
||||||
ImportSourceResourceIden::ModelType,
|
ImportSourceResourceIden::ModelType,
|
||||||
ImportSourceResourceIden::ModelId,
|
ImportSourceResourceIden::ModelId,
|
||||||
ImportSourceResourceIden::Snapshot,
|
ImportSourceResourceIden::ContentHash,
|
||||||
])
|
])
|
||||||
.to_owned(),
|
.to_owned(),
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
use crate::client_db::ClientDb;
|
use crate::client_db::{ClientDb, WriteDb};
|
||||||
use crate::error::Result;
|
use crate::error::Result;
|
||||||
use crate::models::{ImportSource, ImportSourceIden};
|
use crate::models::{ImportSource, ImportSourceIden};
|
||||||
use crate::util::UpdateSource;
|
use crate::util::UpdateSource;
|
||||||
@@ -25,7 +25,9 @@ impl<'a> ClientDb<'a> {
|
|||||||
let sources = self.list_import_sources(workspace_id)?;
|
let sources = self.list_import_sources(workspace_id)?;
|
||||||
Ok(sources.into_iter().find(|s| s.importer == importer && s.origin == origin))
|
Ok(sources.into_iter().find(|s| s.importer == importer && s.origin == origin))
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> WriteDb<'a> {
|
||||||
pub fn upsert_import_source(
|
pub fn upsert_import_source(
|
||||||
&self,
|
&self,
|
||||||
import_source: &ImportSource,
|
import_source: &ImportSource,
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
use crate::client_db::ClientDb;
|
use crate::client_db::{ClientDb, WriteDb};
|
||||||
use crate::error::Result;
|
use crate::error::Result;
|
||||||
use crate::models::{KeyValue, KeyValueIden, UpsertModelInfo};
|
use crate::models::{KeyValue, KeyValueIden, UpsertModelInfo};
|
||||||
use crate::util::UpdateSource;
|
use crate::util::UpdateSource;
|
||||||
@@ -89,7 +89,9 @@ impl<'a> ClientDb<'a> {
|
|||||||
.build_rusqlite(SqliteQueryBuilder);
|
.build_rusqlite(SqliteQueryBuilder);
|
||||||
self.conn().resolve().query_row(sql.as_str(), &*params.as_params(), KeyValue::from_row).ok()
|
self.conn().resolve().query_row(sql.as_str(), &*params.as_params(), KeyValue::from_row).ok()
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> WriteDb<'a> {
|
||||||
pub fn set_key_value_dte(
|
pub fn set_key_value_dte(
|
||||||
&self,
|
&self,
|
||||||
namespace: &str,
|
namespace: &str,
|
||||||
|
|||||||
@@ -24,8 +24,8 @@ mod websocket_events;
|
|||||||
mod websocket_requests;
|
mod websocket_requests;
|
||||||
mod workspace_metas;
|
mod workspace_metas;
|
||||||
pub mod workspaces;
|
pub mod workspaces;
|
||||||
pub use model_changes::PersistedModelChange;
|
|
||||||
pub(crate) use duplicate_name::conflict_free_name;
|
pub(crate) use duplicate_name::conflict_free_name;
|
||||||
|
pub use model_changes::PersistedModelChange;
|
||||||
|
|
||||||
const MAX_HISTORY_ITEMS: usize = 20;
|
const MAX_HISTORY_ITEMS: usize = 20;
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
use crate::client_db::ClientDb;
|
use crate::client_db::{ClientDb, WriteDb};
|
||||||
use crate::error::Result;
|
use crate::error::Result;
|
||||||
use crate::util::ModelPayload;
|
use crate::util::ModelPayload;
|
||||||
use rusqlite::params;
|
use rusqlite::params;
|
||||||
@@ -69,7 +69,9 @@ impl<'a> ClientDb<'a> {
|
|||||||
|
|
||||||
Ok(items.collect::<std::result::Result<Vec<_>, rusqlite::Error>>()?)
|
Ok(items.collect::<std::result::Result<Vec<_>, rusqlite::Error>>()?)
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> WriteDb<'a> {
|
||||||
pub fn prune_model_changes_older_than_days(&self, days: i64) -> Result<usize> {
|
pub fn prune_model_changes_older_than_days(&self, days: i64) -> Result<usize> {
|
||||||
let offset = format!("-{days} days");
|
let offset = format!("-{days} days");
|
||||||
Ok(self.conn().resolve().execute(
|
Ok(self.conn().resolve().execute(
|
||||||
@@ -101,23 +103,36 @@ mod tests {
|
|||||||
use crate::util::{ModelChangeEvent, UpdateSource};
|
use crate::util::{ModelChangeEvent, UpdateSource};
|
||||||
use serde_json::json;
|
use serde_json::json;
|
||||||
|
|
||||||
|
/// Startup bootstraps rows of its own; these tests count only their own.
|
||||||
|
fn clear_changes(query_manager: &crate::query_manager::QueryManager) {
|
||||||
|
query_manager
|
||||||
|
.with_tx(|db| {
|
||||||
|
db.conn().resolve().execute("DELETE FROM model_changes", [])?;
|
||||||
|
Ok::<_, crate::error::Error>(())
|
||||||
|
})
|
||||||
|
.expect("Failed to clear model changes");
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn records_model_changes_for_upsert_and_delete() {
|
fn records_model_changes_for_upsert_and_delete() {
|
||||||
let (query_manager, blob_manager, _rx) = init_in_memory().expect("Failed to init DB");
|
let (query_manager, blob_manager, _rx) = init_in_memory().expect("Failed to init DB");
|
||||||
let db = query_manager.connect();
|
clear_changes(&query_manager);
|
||||||
|
|
||||||
let workspace = db
|
let workspace = query_manager
|
||||||
.upsert_workspace(
|
.with_tx(|db| {
|
||||||
&Workspace {
|
db.upsert_workspace(
|
||||||
name: "Changes Test".to_string(),
|
&Workspace {
|
||||||
setting_follow_redirects: true,
|
name: "Changes Test".to_string(),
|
||||||
setting_validate_certificates: true,
|
setting_follow_redirects: true,
|
||||||
..Default::default()
|
setting_validate_certificates: true,
|
||||||
},
|
..Default::default()
|
||||||
&UpdateSource::Sync,
|
},
|
||||||
)
|
&UpdateSource::Sync,
|
||||||
|
)
|
||||||
|
})
|
||||||
.expect("Failed to upsert workspace");
|
.expect("Failed to upsert workspace");
|
||||||
|
|
||||||
|
let db = query_manager.connect();
|
||||||
let created_changes = db.list_model_changes_after(0, 10).expect("Failed to list changes");
|
let created_changes = db.list_model_changes_after(0, 10).expect("Failed to list changes");
|
||||||
assert_eq!(created_changes.len(), 1);
|
assert_eq!(created_changes.len(), 1);
|
||||||
assert_eq!(created_changes[0].payload.model.id(), workspace.id);
|
assert_eq!(created_changes[0].payload.model.id(), workspace.id);
|
||||||
@@ -128,9 +143,14 @@ mod tests {
|
|||||||
));
|
));
|
||||||
assert!(matches!(created_changes[0].payload.update_source, UpdateSource::Sync));
|
assert!(matches!(created_changes[0].payload.update_source, UpdateSource::Sync));
|
||||||
|
|
||||||
db.delete_workspace_by_id(&workspace.id, &UpdateSource::Sync, &blob_manager)
|
drop(db);
|
||||||
|
query_manager
|
||||||
|
.with_tx(|db| {
|
||||||
|
db.delete_workspace_by_id(&workspace.id, &UpdateSource::Sync, &blob_manager)
|
||||||
|
})
|
||||||
.expect("Failed to delete workspace");
|
.expect("Failed to delete workspace");
|
||||||
|
|
||||||
|
let db = query_manager.connect();
|
||||||
let all_changes = db.list_model_changes_after(0, 10).expect("Failed to list changes");
|
let all_changes = db.list_model_changes_after(0, 10).expect("Failed to list changes");
|
||||||
assert_eq!(all_changes.len(), 2);
|
assert_eq!(all_changes.len(), 2);
|
||||||
assert!(matches!(all_changes[1].payload.change, ModelChangeEvent::Delete));
|
assert!(matches!(all_changes[1].payload.change, ModelChangeEvent::Delete));
|
||||||
@@ -146,19 +166,23 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn prunes_old_model_changes() {
|
fn prunes_old_model_changes() {
|
||||||
let (query_manager, _blob_manager, _rx) = init_in_memory().expect("Failed to init DB");
|
let (query_manager, _blob_manager, _rx) = init_in_memory().expect("Failed to init DB");
|
||||||
|
clear_changes(&query_manager);
|
||||||
|
|
||||||
|
query_manager
|
||||||
|
.with_tx(|db| {
|
||||||
|
db.upsert_workspace(
|
||||||
|
&Workspace {
|
||||||
|
name: "Prune Test".to_string(),
|
||||||
|
setting_follow_redirects: true,
|
||||||
|
setting_validate_certificates: true,
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
&UpdateSource::Sync,
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.expect("Failed to upsert workspace");
|
||||||
|
|
||||||
let db = query_manager.connect();
|
let db = query_manager.connect();
|
||||||
|
|
||||||
db.upsert_workspace(
|
|
||||||
&Workspace {
|
|
||||||
name: "Prune Test".to_string(),
|
|
||||||
setting_follow_redirects: true,
|
|
||||||
setting_validate_certificates: true,
|
|
||||||
..Default::default()
|
|
||||||
},
|
|
||||||
&UpdateSource::Sync,
|
|
||||||
)
|
|
||||||
.expect("Failed to upsert workspace");
|
|
||||||
|
|
||||||
let changes = db.list_model_changes_after(0, 10).expect("Failed to list changes");
|
let changes = db.list_model_changes_after(0, 10).expect("Failed to list changes");
|
||||||
assert_eq!(changes.len(), 1);
|
assert_eq!(changes.len(), 1);
|
||||||
|
|
||||||
@@ -170,31 +194,41 @@ mod tests {
|
|||||||
)
|
)
|
||||||
.expect("Failed to age model change row");
|
.expect("Failed to age model change row");
|
||||||
|
|
||||||
let pruned =
|
drop(db);
|
||||||
db.prune_model_changes_older_than_days(30).expect("Failed to prune model changes");
|
let pruned = query_manager
|
||||||
|
.with_tx(|db| db.prune_model_changes_older_than_days(30))
|
||||||
|
.expect("Failed to prune model changes");
|
||||||
assert_eq!(pruned, 1);
|
assert_eq!(pruned, 1);
|
||||||
assert!(db.list_model_changes_after(0, 10).expect("Failed to list changes").is_empty());
|
assert!(
|
||||||
|
query_manager
|
||||||
|
.connect()
|
||||||
|
.list_model_changes_after(0, 10)
|
||||||
|
.expect("Failed to list changes")
|
||||||
|
.is_empty()
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn list_model_changes_since_uses_timestamp_with_id_tiebreaker() {
|
fn list_model_changes_since_uses_timestamp_with_id_tiebreaker() {
|
||||||
let (query_manager, blob_manager, _rx) = init_in_memory().expect("Failed to init DB");
|
let (query_manager, blob_manager, _rx) = init_in_memory().expect("Failed to init DB");
|
||||||
|
clear_changes(&query_manager);
|
||||||
|
|
||||||
|
query_manager
|
||||||
|
.with_tx(|db| {
|
||||||
|
let workspace = db.upsert_workspace(
|
||||||
|
&Workspace {
|
||||||
|
name: "Cursor Test".to_string(),
|
||||||
|
setting_follow_redirects: true,
|
||||||
|
setting_validate_certificates: true,
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
&UpdateSource::Sync,
|
||||||
|
)?;
|
||||||
|
db.delete_workspace_by_id(&workspace.id, &UpdateSource::Sync, &blob_manager)
|
||||||
|
})
|
||||||
|
.expect("Failed to seed changes");
|
||||||
|
|
||||||
let db = query_manager.connect();
|
let db = query_manager.connect();
|
||||||
|
|
||||||
let workspace = db
|
|
||||||
.upsert_workspace(
|
|
||||||
&Workspace {
|
|
||||||
name: "Cursor Test".to_string(),
|
|
||||||
setting_follow_redirects: true,
|
|
||||||
setting_validate_certificates: true,
|
|
||||||
..Default::default()
|
|
||||||
},
|
|
||||||
&UpdateSource::Sync,
|
|
||||||
)
|
|
||||||
.expect("Failed to upsert workspace");
|
|
||||||
db.delete_workspace_by_id(&workspace.id, &UpdateSource::Sync, &blob_manager)
|
|
||||||
.expect("Failed to delete workspace");
|
|
||||||
|
|
||||||
let all = db.list_model_changes_after(0, 10).expect("Failed to list changes");
|
let all = db.list_model_changes_after(0, 10).expect("Failed to list changes");
|
||||||
assert_eq!(all.len(), 2);
|
assert_eq!(all.len(), 2);
|
||||||
|
|
||||||
@@ -213,19 +247,23 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn prunes_old_model_changes_by_hours() {
|
fn prunes_old_model_changes_by_hours() {
|
||||||
let (query_manager, _blob_manager, _rx) = init_in_memory().expect("Failed to init DB");
|
let (query_manager, _blob_manager, _rx) = init_in_memory().expect("Failed to init DB");
|
||||||
|
clear_changes(&query_manager);
|
||||||
|
|
||||||
|
query_manager
|
||||||
|
.with_tx(|db| {
|
||||||
|
db.upsert_workspace(
|
||||||
|
&Workspace {
|
||||||
|
name: "Prune Hour Test".to_string(),
|
||||||
|
setting_follow_redirects: true,
|
||||||
|
setting_validate_certificates: true,
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
&UpdateSource::Sync,
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.expect("Failed to upsert workspace");
|
||||||
|
|
||||||
let db = query_manager.connect();
|
let db = query_manager.connect();
|
||||||
|
|
||||||
db.upsert_workspace(
|
|
||||||
&Workspace {
|
|
||||||
name: "Prune Hour Test".to_string(),
|
|
||||||
setting_follow_redirects: true,
|
|
||||||
setting_validate_certificates: true,
|
|
||||||
..Default::default()
|
|
||||||
},
|
|
||||||
&UpdateSource::Sync,
|
|
||||||
)
|
|
||||||
.expect("Failed to upsert workspace");
|
|
||||||
|
|
||||||
let changes = db.list_model_changes_after(0, 10).expect("Failed to list changes");
|
let changes = db.list_model_changes_after(0, 10).expect("Failed to list changes");
|
||||||
assert_eq!(changes.len(), 1);
|
assert_eq!(changes.len(), 1);
|
||||||
|
|
||||||
@@ -237,14 +275,17 @@ mod tests {
|
|||||||
)
|
)
|
||||||
.expect("Failed to age model change row");
|
.expect("Failed to age model change row");
|
||||||
|
|
||||||
let pruned =
|
drop(db);
|
||||||
db.prune_model_changes_older_than_hours(1).expect("Failed to prune model changes");
|
let pruned = query_manager
|
||||||
|
.with_tx(|db| db.prune_model_changes_older_than_hours(1))
|
||||||
|
.expect("Failed to prune model changes");
|
||||||
assert_eq!(pruned, 1);
|
assert_eq!(pruned, 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn list_model_changes_deserializes_http_response_event_payload() {
|
fn list_model_changes_deserializes_http_response_event_payload() {
|
||||||
let (query_manager, _blob_manager, _rx) = init_in_memory().expect("Failed to init DB");
|
let (query_manager, _blob_manager, _rx) = init_in_memory().expect("Failed to init DB");
|
||||||
|
clear_changes(&query_manager);
|
||||||
let db = query_manager.connect();
|
let db = query_manager.connect();
|
||||||
|
|
||||||
let payload = json!({
|
let payload = json!({
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
use crate::client_db::ClientDb;
|
use crate::client_db::{ClientDb, WriteDb};
|
||||||
use crate::error::Result;
|
use crate::error::Result;
|
||||||
use crate::models::{PluginKeyValue, PluginKeyValueIden};
|
use crate::models::{PluginKeyValue, PluginKeyValueIden};
|
||||||
use sea_query::ExprTrait;
|
use sea_query::ExprTrait;
|
||||||
@@ -22,7 +22,9 @@ impl<'a> ClientDb<'a> {
|
|||||||
.query_row(sql.as_str(), &*params.as_params(), |row| row.try_into())
|
.query_row(sql.as_str(), &*params.as_params(), |row| row.try_into())
|
||||||
.ok()
|
.ok()
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> WriteDb<'a> {
|
||||||
pub fn set_plugin_key_value(
|
pub fn set_plugin_key_value(
|
||||||
&self,
|
&self,
|
||||||
plugin_name: &str,
|
plugin_name: &str,
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
use crate::client_db::ClientDb;
|
use crate::client_db::{ClientDb, WriteDb};
|
||||||
use crate::error::Result;
|
use crate::error::Result;
|
||||||
use crate::models::{Plugin, PluginIden};
|
use crate::models::{Plugin, PluginIden};
|
||||||
use crate::util::UpdateSource;
|
use crate::util::UpdateSource;
|
||||||
@@ -15,7 +15,9 @@ impl<'a> ClientDb<'a> {
|
|||||||
pub fn list_plugins(&self) -> Result<Vec<Plugin>> {
|
pub fn list_plugins(&self) -> Result<Vec<Plugin>> {
|
||||||
self.find_all()
|
self.find_all()
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> WriteDb<'a> {
|
||||||
pub fn delete_plugin(&self, plugin: &Plugin, source: &UpdateSource) -> Result<Plugin> {
|
pub fn delete_plugin(&self, plugin: &Plugin, source: &UpdateSource) -> Result<Plugin> {
|
||||||
self.delete(plugin, source)
|
self.delete(plugin, source)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,52 +1,61 @@
|
|||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
|
|
||||||
use crate::client_db::ClientDb;
|
use crate::client_db::{ClientDb, WriteDb};
|
||||||
use crate::error::Result;
|
use crate::error::Result;
|
||||||
use crate::models::{EditorKeymap, Settings, SettingsIden};
|
use crate::models::{EditorKeymap, Settings, SettingsIden};
|
||||||
use crate::util::UpdateSource;
|
use crate::util::UpdateSource;
|
||||||
|
|
||||||
impl<'a> ClientDb<'a> {
|
impl<'a> ClientDb<'a> {
|
||||||
|
/// The settings row, or the defaults if it has not been written yet.
|
||||||
|
/// [`WriteDb::ensure_settings`] persists it at startup.
|
||||||
pub fn get_settings(&self) -> Settings {
|
pub fn get_settings(&self) -> Settings {
|
||||||
let id = "default".to_string();
|
self.find_optional::<Settings>(SettingsIden::Id, "default").unwrap_or_else(default_settings)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if let Some(s) = self.find_optional::<Settings>(SettingsIden::Id, &id) {
|
impl<'a> WriteDb<'a> {
|
||||||
return s;
|
/// Create the settings row if it does not exist.
|
||||||
};
|
pub fn ensure_settings(&self) -> Result<Settings> {
|
||||||
|
if let Some(s) = self.find_optional::<Settings>(SettingsIden::Id, "default") {
|
||||||
let settings = Settings {
|
return Ok(s);
|
||||||
model: "settings".to_string(),
|
}
|
||||||
id,
|
self.upsert(&default_settings(), &UpdateSource::Background)
|
||||||
created_at: Default::default(),
|
|
||||||
updated_at: Default::default(),
|
|
||||||
|
|
||||||
appearance: "system".to_string(),
|
|
||||||
client_certificates: Vec::new(),
|
|
||||||
editor_font_size: 12,
|
|
||||||
editor_font: None,
|
|
||||||
editor_keymap: EditorKeymap::Default,
|
|
||||||
editor_soft_wrap: true,
|
|
||||||
interface_font_size: 14,
|
|
||||||
interface_scale: 1.0,
|
|
||||||
interface_font: None,
|
|
||||||
hide_window_controls: false,
|
|
||||||
use_native_titlebar: false,
|
|
||||||
open_workspace_new_window: None,
|
|
||||||
proxy: None,
|
|
||||||
theme_dark: "yaak-dark".to_string(),
|
|
||||||
theme_light: "yaak-light".to_string(),
|
|
||||||
update_channel: "stable".to_string(),
|
|
||||||
autoupdate: true,
|
|
||||||
colored_methods: false,
|
|
||||||
hide_license_badge: false,
|
|
||||||
prompt_feedback: true,
|
|
||||||
auto_download_updates: true,
|
|
||||||
check_notifications: true,
|
|
||||||
hotkeys: HashMap::new(),
|
|
||||||
};
|
|
||||||
self.upsert(&settings, &UpdateSource::Background).expect("Failed to upsert settings")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn upsert_settings(&self, settings: &Settings, source: &UpdateSource) -> Result<Settings> {
|
pub fn upsert_settings(&self, settings: &Settings, source: &UpdateSource) -> Result<Settings> {
|
||||||
self.upsert(settings, source)
|
self.upsert(settings, source)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn default_settings() -> Settings {
|
||||||
|
Settings {
|
||||||
|
model: "settings".to_string(),
|
||||||
|
id: "default".to_string(),
|
||||||
|
created_at: Default::default(),
|
||||||
|
updated_at: Default::default(),
|
||||||
|
|
||||||
|
appearance: "system".to_string(),
|
||||||
|
client_certificates: Vec::new(),
|
||||||
|
editor_font_size: 12,
|
||||||
|
editor_font: None,
|
||||||
|
editor_keymap: EditorKeymap::Default,
|
||||||
|
editor_soft_wrap: true,
|
||||||
|
interface_font_size: 14,
|
||||||
|
interface_scale: 1.0,
|
||||||
|
interface_font: None,
|
||||||
|
hide_window_controls: false,
|
||||||
|
use_native_titlebar: false,
|
||||||
|
open_workspace_new_window: None,
|
||||||
|
proxy: None,
|
||||||
|
theme_dark: "yaak-dark".to_string(),
|
||||||
|
theme_light: "yaak-light".to_string(),
|
||||||
|
update_channel: "stable".to_string(),
|
||||||
|
autoupdate: true,
|
||||||
|
colored_methods: false,
|
||||||
|
hide_license_badge: false,
|
||||||
|
prompt_feedback: true,
|
||||||
|
auto_download_updates: true,
|
||||||
|
check_notifications: true,
|
||||||
|
hotkeys: HashMap::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
use crate::client_db::ClientDb;
|
use crate::client_db::{ClientDb, WriteDb};
|
||||||
use crate::error::Result;
|
use crate::error::Result;
|
||||||
use crate::models::{SyncState, SyncStateIden, UpsertModelInfo};
|
use crate::models::{SyncState, SyncStateIden, UpsertModelInfo};
|
||||||
use crate::util::UpdateSource;
|
use crate::util::UpdateSource;
|
||||||
@@ -12,10 +12,6 @@ impl<'a> ClientDb<'a> {
|
|||||||
self.find_one(SyncStateIden::Id, id)
|
self.find_one(SyncStateIden::Id, id)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn upsert_sync_state(&self, sync_state: &SyncState) -> Result<SyncState> {
|
|
||||||
self.upsert(sync_state, &UpdateSource::Sync)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn list_sync_states_for_workspace(
|
pub fn list_sync_states_for_workspace(
|
||||||
&self,
|
&self,
|
||||||
workspace_id: &str,
|
workspace_id: &str,
|
||||||
@@ -34,6 +30,12 @@ impl<'a> ClientDb<'a> {
|
|||||||
let items = stmt.query_map(&*params.as_params(), SyncState::from_row)?;
|
let items = stmt.query_map(&*params.as_params(), SyncState::from_row)?;
|
||||||
Ok(items.map(|v| v.unwrap()).collect())
|
Ok(items.map(|v| v.unwrap()).collect())
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> WriteDb<'a> {
|
||||||
|
pub fn upsert_sync_state(&self, sync_state: &SyncState) -> Result<SyncState> {
|
||||||
|
self.upsert(sync_state, &UpdateSource::Sync)
|
||||||
|
}
|
||||||
|
|
||||||
pub fn delete_sync_state(&self, sync_state: &SyncState) -> Result<SyncState> {
|
pub fn delete_sync_state(&self, sync_state: &SyncState) -> Result<SyncState> {
|
||||||
self.delete(sync_state, &UpdateSource::Sync)
|
self.delete(sync_state, &UpdateSource::Sync)
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
use crate::client_db::ClientDb;
|
use crate::client_db::{ClientDb, WriteDb};
|
||||||
use crate::error::Result;
|
use crate::error::Result;
|
||||||
use crate::models::{WebsocketConnection, WebsocketConnectionIden, WebsocketConnectionState};
|
use crate::models::{WebsocketConnection, WebsocketConnectionIden, WebsocketConnectionState};
|
||||||
use crate::queries::MAX_HISTORY_ITEMS;
|
use crate::queries::MAX_HISTORY_ITEMS;
|
||||||
@@ -13,6 +13,22 @@ impl<'a> ClientDb<'a> {
|
|||||||
self.find_one(WebsocketConnectionIden::Id, id)
|
self.find_one(WebsocketConnectionIden::Id, id)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn list_websocket_connections(
|
||||||
|
&self,
|
||||||
|
workspace_id: &str,
|
||||||
|
) -> Result<Vec<WebsocketConnection>> {
|
||||||
|
self.find_many(WebsocketConnectionIden::WorkspaceId, workspace_id, None)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn list_websocket_connections_for_request(
|
||||||
|
&self,
|
||||||
|
request_id: &str,
|
||||||
|
) -> Result<Vec<WebsocketConnection>> {
|
||||||
|
self.find_many(WebsocketConnectionIden::RequestId, request_id, None)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> WriteDb<'a> {
|
||||||
pub fn delete_all_websocket_connections_for_request(
|
pub fn delete_all_websocket_connections_for_request(
|
||||||
&self,
|
&self,
|
||||||
request_id: &str,
|
request_id: &str,
|
||||||
@@ -37,20 +53,6 @@ impl<'a> ClientDb<'a> {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn list_websocket_connections(
|
|
||||||
&self,
|
|
||||||
workspace_id: &str,
|
|
||||||
) -> Result<Vec<WebsocketConnection>> {
|
|
||||||
self.find_many(WebsocketConnectionIden::WorkspaceId, workspace_id, None)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn list_websocket_connections_for_request(
|
|
||||||
&self,
|
|
||||||
request_id: &str,
|
|
||||||
) -> Result<Vec<WebsocketConnection>> {
|
|
||||||
self.find_many(WebsocketConnectionIden::RequestId, request_id, None)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn delete_websocket_connection(
|
pub fn delete_websocket_connection(
|
||||||
&self,
|
&self,
|
||||||
websocket_connection: &WebsocketConnection,
|
websocket_connection: &WebsocketConnection,
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
use crate::client_db::ClientDb;
|
use crate::client_db::{ClientDb, WriteDb};
|
||||||
use crate::error::Result;
|
use crate::error::Result;
|
||||||
use crate::models::{WebsocketEvent, WebsocketEventIden};
|
use crate::models::{WebsocketEvent, WebsocketEventIden};
|
||||||
use crate::util::UpdateSource;
|
use crate::util::UpdateSource;
|
||||||
@@ -11,7 +11,9 @@ impl<'a> ClientDb<'a> {
|
|||||||
pub fn list_websocket_events(&self, connection_id: &str) -> Result<Vec<WebsocketEvent>> {
|
pub fn list_websocket_events(&self, connection_id: &str) -> Result<Vec<WebsocketEvent>> {
|
||||||
self.find_many(WebsocketEventIden::ConnectionId, connection_id, None)
|
self.find_many(WebsocketEventIden::ConnectionId, connection_id, None)
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> WriteDb<'a> {
|
||||||
pub fn upsert_websocket_event(
|
pub fn upsert_websocket_event(
|
||||||
&self,
|
&self,
|
||||||
websocket_event: &WebsocketEvent,
|
websocket_event: &WebsocketEvent,
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
use super::{conflict_free_name, merge_headers};
|
use super::{conflict_free_name, merge_headers};
|
||||||
use crate::client_db::ClientDb;
|
use crate::client_db::{ClientDb, WriteDb};
|
||||||
use crate::error::Result;
|
use crate::error::Result;
|
||||||
use crate::models::{
|
use crate::models::{
|
||||||
AnyModel, Folder, FolderIden, HttpRequestHeader, ResolvedHttpRequestSettings, ResolvedSetting,
|
AnyModel, Folder, FolderIden, HttpRequestHeader, ResolvedHttpRequestSettings, ResolvedSetting,
|
||||||
@@ -34,50 +34,6 @@ impl<'a> ClientDb<'a> {
|
|||||||
Ok(children)
|
Ok(children)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn delete_websocket_request(
|
|
||||||
&self,
|
|
||||||
websocket_request: &WebsocketRequest,
|
|
||||||
source: &UpdateSource,
|
|
||||||
) -> Result<WebsocketRequest> {
|
|
||||||
self.delete_all_websocket_connections_for_request(websocket_request.id.as_str(), source)?;
|
|
||||||
self.delete(websocket_request, source)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn delete_websocket_request_by_id(
|
|
||||||
&self,
|
|
||||||
id: &str,
|
|
||||||
source: &UpdateSource,
|
|
||||||
) -> Result<WebsocketRequest> {
|
|
||||||
let request = self.get_websocket_request(id)?;
|
|
||||||
self.delete_websocket_request(&request, source)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn duplicate_websocket_request(
|
|
||||||
&self,
|
|
||||||
websocket_request: &WebsocketRequest,
|
|
||||||
source: &UpdateSource,
|
|
||||||
) -> Result<WebsocketRequest> {
|
|
||||||
let mut websocket_request = websocket_request.clone();
|
|
||||||
websocket_request.id = "".to_string();
|
|
||||||
websocket_request.sort_priority = websocket_request.sort_priority + 0.001;
|
|
||||||
let sibling_names = self
|
|
||||||
.list_websocket_requests(&websocket_request.workspace_id)?
|
|
||||||
.into_iter()
|
|
||||||
.filter(|m| m.folder_id == websocket_request.folder_id)
|
|
||||||
.map(|m| m.name)
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
websocket_request.name = conflict_free_name(&websocket_request.name, &sibling_names);
|
|
||||||
self.upsert(&websocket_request, source)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn upsert_websocket_request(
|
|
||||||
&self,
|
|
||||||
websocket_request: &WebsocketRequest,
|
|
||||||
source: &UpdateSource,
|
|
||||||
) -> Result<WebsocketRequest> {
|
|
||||||
self.upsert(websocket_request, source)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn resolve_auth_for_websocket_request(
|
pub fn resolve_auth_for_websocket_request(
|
||||||
&self,
|
&self,
|
||||||
websocket_request: &WebsocketRequest,
|
websocket_request: &WebsocketRequest,
|
||||||
@@ -168,3 +124,49 @@ impl<'a> ClientDb<'a> {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl<'a> WriteDb<'a> {
|
||||||
|
pub fn delete_websocket_request(
|
||||||
|
&self,
|
||||||
|
websocket_request: &WebsocketRequest,
|
||||||
|
source: &UpdateSource,
|
||||||
|
) -> Result<WebsocketRequest> {
|
||||||
|
self.delete_all_websocket_connections_for_request(websocket_request.id.as_str(), source)?;
|
||||||
|
self.delete(websocket_request, source)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn delete_websocket_request_by_id(
|
||||||
|
&self,
|
||||||
|
id: &str,
|
||||||
|
source: &UpdateSource,
|
||||||
|
) -> Result<WebsocketRequest> {
|
||||||
|
let request = self.get_websocket_request(id)?;
|
||||||
|
self.delete_websocket_request(&request, source)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn duplicate_websocket_request(
|
||||||
|
&self,
|
||||||
|
websocket_request: &WebsocketRequest,
|
||||||
|
source: &UpdateSource,
|
||||||
|
) -> Result<WebsocketRequest> {
|
||||||
|
let mut websocket_request = websocket_request.clone();
|
||||||
|
websocket_request.id = "".to_string();
|
||||||
|
websocket_request.sort_priority = websocket_request.sort_priority + 0.001;
|
||||||
|
let sibling_names = self
|
||||||
|
.list_websocket_requests(&websocket_request.workspace_id)?
|
||||||
|
.into_iter()
|
||||||
|
.filter(|m| m.folder_id == websocket_request.folder_id)
|
||||||
|
.map(|m| m.name)
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
websocket_request.name = conflict_free_name(&websocket_request.name, &sibling_names);
|
||||||
|
self.upsert(&websocket_request, source)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn upsert_websocket_request(
|
||||||
|
&self,
|
||||||
|
websocket_request: &WebsocketRequest,
|
||||||
|
source: &UpdateSource,
|
||||||
|
) -> Result<WebsocketRequest> {
|
||||||
|
self.upsert(websocket_request, source)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
use crate::client_db::ClientDb;
|
use crate::client_db::{ClientDb, WriteDb};
|
||||||
use crate::error::Result;
|
use crate::error::Result;
|
||||||
use crate::models::{WorkspaceMeta, WorkspaceMetaIden};
|
use crate::models::{WorkspaceMeta, WorkspaceMetaIden};
|
||||||
use crate::util::UpdateSource;
|
use crate::util::UpdateSource;
|
||||||
@@ -10,18 +10,12 @@ impl<'a> ClientDb<'a> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn list_workspace_metas(&self, workspace_id: &str) -> Result<Vec<WorkspaceMeta>> {
|
pub fn list_workspace_metas(&self, workspace_id: &str) -> Result<Vec<WorkspaceMeta>> {
|
||||||
let mut workspace_metas =
|
self.find_many(WorkspaceMetaIden::WorkspaceId, workspace_id, None)
|
||||||
self.find_many(WorkspaceMetaIden::WorkspaceId, workspace_id, None)?;
|
|
||||||
|
|
||||||
if workspace_metas.is_empty() {
|
|
||||||
let wm = WorkspaceMeta { workspace_id: workspace_id.to_string(), ..Default::default() };
|
|
||||||
workspace_metas.push(self.upsert_workspace_meta(&wm, &UpdateSource::Background)?)
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(workspace_metas)
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub fn get_or_create_workspace_meta(&self, workspace_id: &str) -> Result<WorkspaceMeta> {
|
impl<'a> WriteDb<'a> {
|
||||||
|
pub fn ensure_workspace_meta(&self, workspace_id: &str) -> Result<WorkspaceMeta> {
|
||||||
let workspace_meta = self.get_workspace_meta(workspace_id);
|
let workspace_meta = self.get_workspace_meta(workspace_id);
|
||||||
if let Some(workspace_meta) = workspace_meta {
|
if let Some(workspace_meta) = workspace_meta {
|
||||||
return Ok(workspace_meta);
|
return Ok(workspace_meta);
|
||||||
|
|||||||
Loaded 100 of 158 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user