Compare commits

...
Author SHA1 Message Date
Gregory SchierandClaude Opus 5 08733bf74d feat(models): raise the pool ceiling and report its state when acquisition is slow
Two changes that go together, because the first is untestable without the second.

`max_size` goes 20 → 50. The comment justifying 20 was out of date: it cited the
256 open-file soft limit macOS gives GUI apps, but `run()` has since called
`rlimit::increase_nofile_limit(10240)` before any pool is opened, so the ceiling
it was sized against is gone. 50 WAL connections is roughly 150 descriptors
against 10240, and only `min_idle` is opened up front — r2d2 creates the rest on
demand — so the idle cost is unchanged. The comment now says what actually
bounds the number: commands nest a couple of connections each, and since #542
every frontend command dispatches as its own task, so they arrive together.

On its own that is a guess with no way to check itself. A pool that cannot hand
out a connection fails with `Error(None)` and nothing else, whether every
connection is checked out or none could be opened — unrelated problems with
identical symptoms, and raising the ceiling only helps the first. So both pools
now acquire through one helper that times the wait, warns past a second, and
folds the pool's state into `Error::PoolTimeout`. The error a command returns
now says which failure it was, which is what the next report needs to be worth
anything.

Blob pool sizing is untouched; nothing points at it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-10 17:09:02 -07:00
Gregory SchierandClaude Opus 5 1655aaa507 fix(send): stop the HTTP response-event writer panicking on a pool timeout
The event task spawned per send still reached `connect().unwrap()`. A pool
timeout there panicked the task and took every later timeline event for that
send with it, straight past the `warn!` branch already sitting underneath. The
acquisition now joins the upsert in the same `if let Err`.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-10 17:09:02 -07:00
Gregory SchierandClaude Opus 5 c9e884d4fe fix(models): return a database error instead of panicking when the pool is exhausted
Two users on 2026.7.x reported the app going half-dead: local editing kept
working, but Send did nothing and every encrypted secret rendered blank until
they restarted. The webview console carried a Rust task panic —

    Delete task failed: task 1314 panicked with message
    "Failed to get new DB connection from the pool: Error(None)"

`Error(None)` is r2d2's acquire timeout. `QueryManager::connect` and `with_tx`
turned that timeout into `expect`, so a pool that was momentarily full took down
whatever task asked for a connection instead of reporting a failure the caller
could show, retry, or ignore. Every DB-backed path shares those two functions,
which is why one stalled pool reads as "Send is dead and the secrets are gone".

Acquisition is now fallible end to end: `connect()` and `BlobManager::connect()`
return `Result`, and so do the `db()`/`blobs()` accessors on every host. Call
sites propagate with `?` where they already returned a result; the fire-and-forget
writers (streaming events, the model-change poller) log and carry on. `with_conn`
had no callers and only added a third panic, so it is gone.

Two places held a pooled connection across work that has nothing to do with the
database and can block for a long time — the OS keyring in
`EncryptionManager::get_workspace_key`, and the sync directory walk in
`cmd_sync_calculate`. Both now hand the connection back first. Those are the
paths behind the two visible symptoms.

Not fixed here: the gRPC streaming block in yaak-app-client still `.unwrap()`s
its database writes, as it did before, so acquisition failures panic there too.
`ProxyQueryManager` in the separate proxy app keeps its own `expect`.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-10 17:09:02 -07:00
Gregory SchierandClaude Opus 5 7f8b7bf567 feat(import): remember the user's import selection (#619)
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-10 15:26:43 -07:00
Gregory Schier 096e83a7bd chore(deps): patch open security advisories across npm deps (#630) 2026-09-10 14:34:00 -07:00
gschier 89ce84cefe Deploying to main from @ mountain-loop/yaak@d5d2a64c32 🚀 2026-09-10 15:37:06 +00:00
Gregory Schier d5d2a64c32 fix(cli): focus the agent skill description on when to use it (#625) 2026-09-09 08:50:26 -07:00
Gregory Schier d2d4b80a09 feat(import): merge re-imports from a linked source instead of duplicating (#618) 2026-09-01 11:12:07 -07:00
Gregory Schier d461c982ec Don't block window creation on plugin runtime boot (#616) 2026-09-01 09:14:50 -07:00
Gregory SchierandClaude Fable 5 8eebee460e fix(pair-editor): remount the editor when its stateKey changes (#617)
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-09-01 08:58:55 -07:00
Gregory SchierandClaude Opus 5 81a2a5d955 feat(import): add stable per-resource source keys to the importer contract (#614)
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-01 08:11:54 -07:00
Gregory SchierandClaude Opus 5 e63a87718c fix(tooling): keep the formatter off generated files in every entry point (#615)
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-01 07:40:42 -07:00
Gregory Schier 222ea9cb83 fix(editor): opt editors out of macOS Writing Tools suggestions
A "Write with Siri" pill appears over empty editors on the macOS 27 beta,
because Codemirror's contentDOM is a contenteditable like any other. The
`writingsuggestions` attribute opts an editable element out, and setting
it here covers every editor at once.

If the pill turns out to be separate from writing suggestions, the
remaining lever is WKWebView's writingToolsBehavior, which would disable
Writing Tools for the whole window.
2026-08-31 10:55:05 -07:00
Gregory Schier 360c098b09 fix(grpc): remove the dead Refresh item from the method picker
It has never had an onSelect. Introduced inert in #193 and carried
through the codebase split, so clicking it only ever closed the dropdown.
Reload Schema in the message editor's schema dropdown does the job it
looked like it was for.
2026-08-31 10:54:40 -07:00
Gregory Schier fce1039bac feat(grpc): generate an example message from the method schema (#613) 2026-08-31 10:44:31 -07:00
Gregory Schier f18f93d613 Stage imports before committing (#571) 2026-08-31 10:20:44 -07:00
Gregory SchierandClaude Opus 5 661a384bed Faster codemirror search match counting (#612)
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-31 10:09:50 -07:00
141 changed files with 8630 additions and 1666 deletions

No files matched your search

+34
View File
@@ -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
-3
View File
@@ -1,3 +0,0 @@
**/bindings/**
**/routeTree.gen.ts
crates/yaak-templates/pkg/**
Generated
+4
View File
@@ -11223,9 +11223,12 @@ version = "0.1.0"
dependencies = [ dependencies = [
"async-trait", "async-trait",
"base64 0.22.1", "base64 0.22.1",
"chrono",
"log 0.4.29", "log 0.4.29",
"md5 0.8.0", "md5 0.8.0",
"rusqlite",
"serde_json", "serde_json",
"sha2",
"tempfile", "tempfile",
"thiserror 2.0.17", "thiserror 2.0.17",
"tokio", "tokio",
@@ -11592,6 +11595,7 @@ dependencies = [
"serde", "serde",
"serde_json", "serde_json",
"sha2", "sha2",
"tempfile",
"thiserror 2.0.17", "thiserror 2.0.17",
"ts-rs", "ts-rs",
"urlencoding", "urlencoding",
+1 -1
View File
@@ -17,7 +17,7 @@
<br> <br>
<p align="center"> <p align="center">
<!-- sponsors-premium --><a href="https://github.com/MVST-Solutions"><img src="https:&#x2F;&#x2F;github.com&#x2F;MVST-Solutions.png" width="80px" alt="User avatar: MVST-Solutions" /></a>&nbsp;&nbsp;<a href="https://github.com/dharsanb"><img src="https:&#x2F;&#x2F;github.com&#x2F;dharsanb.png" width="80px" alt="User avatar: dharsanb" /></a>&nbsp;&nbsp;<a href="https://github.com/railwayapp"><img src="https:&#x2F;&#x2F;github.com&#x2F;railwayapp.png" width="80px" alt="User avatar: railwayapp" /></a>&nbsp;&nbsp;<a href="https://github.com/caseyamcl"><img src="https:&#x2F;&#x2F;github.com&#x2F;caseyamcl.png" width="80px" alt="User avatar: caseyamcl" /></a>&nbsp;&nbsp;<a href="https://github.com/bytebase"><img src="https:&#x2F;&#x2F;github.com&#x2F;bytebase.png" width="80px" alt="User avatar: bytebase" /></a>&nbsp;&nbsp;<a href="https://github.com/"><img src="https:&#x2F;&#x2F;raw.githubusercontent.com&#x2F;JamesIves&#x2F;github-sponsors-readme-action&#x2F;dev&#x2F;.github&#x2F;assets&#x2F;placeholder.png" width="80px" alt="User avatar: " /></a>&nbsp;&nbsp;<!-- sponsors-premium --> <!-- sponsors-premium --><a href="https://github.com/MVST-Solutions"><img src="https:&#x2F;&#x2F;github.com&#x2F;MVST-Solutions.png" width="80px" alt="User avatar: MVST-Solutions" /></a>&nbsp;&nbsp;<a href="https://github.com/dharsanb"><img src="https:&#x2F;&#x2F;github.com&#x2F;dharsanb.png" width="80px" alt="User avatar: dharsanb" /></a>&nbsp;&nbsp;<a href="https://github.com/railwayapp"><img src="https:&#x2F;&#x2F;github.com&#x2F;railwayapp.png" width="80px" alt="User avatar: railwayapp" /></a>&nbsp;&nbsp;<a href="https://github.com/caseyamcl"><img src="https:&#x2F;&#x2F;github.com&#x2F;caseyamcl.png" width="80px" alt="User avatar: caseyamcl" /></a>&nbsp;&nbsp;<a href="https://github.com/bytebase"><img src="https:&#x2F;&#x2F;github.com&#x2F;bytebase.png" width="80px" alt="User avatar: bytebase" /></a>&nbsp;&nbsp;<a href="https://github.com/rauchg"><img src="https:&#x2F;&#x2F;github.com&#x2F;rauchg.png" width="80px" alt="User avatar: rauchg" /></a>&nbsp;&nbsp;<a href="https://github.com/"><img src="https:&#x2F;&#x2F;raw.githubusercontent.com&#x2F;JamesIves&#x2F;github-sponsors-readme-action&#x2F;dev&#x2F;.github&#x2F;assets&#x2F;placeholder.png" width="80px" alt="User avatar: " /></a>&nbsp;&nbsp;<!-- sponsors-premium -->
</p> </p>
<p align="center"> <p align="center">
<!-- sponsors-base --><a href="https://github.com/seanwash"><img src="https:&#x2F;&#x2F;github.com&#x2F;seanwash.png" width="50px" alt="User avatar: seanwash" /></a>&nbsp;&nbsp;<a href="https://github.com/jerath"><img src="https:&#x2F;&#x2F;github.com&#x2F;jerath.png" width="50px" alt="User avatar: jerath" /></a>&nbsp;&nbsp;<a href="https://github.com/itsa-sh"><img src="https:&#x2F;&#x2F;github.com&#x2F;itsa-sh.png" width="50px" alt="User avatar: itsa-sh" /></a>&nbsp;&nbsp;<a href="https://github.com/dmmulroy"><img src="https:&#x2F;&#x2F;github.com&#x2F;dmmulroy.png" width="50px" alt="User avatar: dmmulroy" /></a>&nbsp;&nbsp;<a href="https://github.com/timcole"><img src="https:&#x2F;&#x2F;github.com&#x2F;timcole.png" width="50px" alt="User avatar: timcole" /></a>&nbsp;&nbsp;<a href="https://github.com/VLZH"><img src="https:&#x2F;&#x2F;github.com&#x2F;VLZH.png" width="50px" alt="User avatar: VLZH" /></a>&nbsp;&nbsp;<a href="https://github.com/terasaka2k"><img src="https:&#x2F;&#x2F;github.com&#x2F;terasaka2k.png" width="50px" alt="User avatar: terasaka2k" /></a>&nbsp;&nbsp;<a href="https://github.com/andriyor"><img src="https:&#x2F;&#x2F;github.com&#x2F;andriyor.png" width="50px" alt="User avatar: andriyor" /></a>&nbsp;&nbsp;<a href="https://github.com/majudhu"><img src="https:&#x2F;&#x2F;github.com&#x2F;majudhu.png" width="50px" alt="User avatar: majudhu" /></a>&nbsp;&nbsp;<a href="https://github.com/axelrindle"><img src="https:&#x2F;&#x2F;github.com&#x2F;axelrindle.png" width="50px" alt="User avatar: axelrindle" /></a>&nbsp;&nbsp;<a href="https://github.com/jirizverina"><img src="https:&#x2F;&#x2F;github.com&#x2F;jirizverina.png" width="50px" alt="User avatar: jirizverina" /></a>&nbsp;&nbsp;<a href="https://github.com/chip-well"><img src="https:&#x2F;&#x2F;github.com&#x2F;chip-well.png" width="50px" alt="User avatar: chip-well" /></a>&nbsp;&nbsp;<a href="https://github.com/GRAYAH"><img src="https:&#x2F;&#x2F;github.com&#x2F;GRAYAH.png" width="50px" alt="User avatar: GRAYAH" /></a>&nbsp;&nbsp;<a href="https://github.com/flashblaze"><img src="https:&#x2F;&#x2F;github.com&#x2F;flashblaze.png" width="50px" alt="User avatar: flashblaze" /></a>&nbsp;&nbsp;<a href="https://github.com/Frostist"><img src="https:&#x2F;&#x2F;github.com&#x2F;Frostist.png" width="50px" alt="User avatar: Frostist" /></a>&nbsp;&nbsp;<a href="https://github.com/PurplProto"><img src="https:&#x2F;&#x2F;github.com&#x2F;PurplProto.png" width="50px" alt="User avatar: PurplProto" /></a>&nbsp;&nbsp;<!-- sponsors-base --> <!-- sponsors-base --><a href="https://github.com/seanwash"><img src="https:&#x2F;&#x2F;github.com&#x2F;seanwash.png" width="50px" alt="User avatar: seanwash" /></a>&nbsp;&nbsp;<a href="https://github.com/jerath"><img src="https:&#x2F;&#x2F;github.com&#x2F;jerath.png" width="50px" alt="User avatar: jerath" /></a>&nbsp;&nbsp;<a href="https://github.com/itsa-sh"><img src="https:&#x2F;&#x2F;github.com&#x2F;itsa-sh.png" width="50px" alt="User avatar: itsa-sh" /></a>&nbsp;&nbsp;<a href="https://github.com/dmmulroy"><img src="https:&#x2F;&#x2F;github.com&#x2F;dmmulroy.png" width="50px" alt="User avatar: dmmulroy" /></a>&nbsp;&nbsp;<a href="https://github.com/timcole"><img src="https:&#x2F;&#x2F;github.com&#x2F;timcole.png" width="50px" alt="User avatar: timcole" /></a>&nbsp;&nbsp;<a href="https://github.com/VLZH"><img src="https:&#x2F;&#x2F;github.com&#x2F;VLZH.png" width="50px" alt="User avatar: VLZH" /></a>&nbsp;&nbsp;<a href="https://github.com/terasaka2k"><img src="https:&#x2F;&#x2F;github.com&#x2F;terasaka2k.png" width="50px" alt="User avatar: terasaka2k" /></a>&nbsp;&nbsp;<a href="https://github.com/andriyor"><img src="https:&#x2F;&#x2F;github.com&#x2F;andriyor.png" width="50px" alt="User avatar: andriyor" /></a>&nbsp;&nbsp;<a href="https://github.com/majudhu"><img src="https:&#x2F;&#x2F;github.com&#x2F;majudhu.png" width="50px" alt="User avatar: majudhu" /></a>&nbsp;&nbsp;<a href="https://github.com/axelrindle"><img src="https:&#x2F;&#x2F;github.com&#x2F;axelrindle.png" width="50px" alt="User avatar: axelrindle" /></a>&nbsp;&nbsp;<a href="https://github.com/jirizverina"><img src="https:&#x2F;&#x2F;github.com&#x2F;jirizverina.png" width="50px" alt="User avatar: jirizverina" /></a>&nbsp;&nbsp;<a href="https://github.com/chip-well"><img src="https:&#x2F;&#x2F;github.com&#x2F;chip-well.png" width="50px" alt="User avatar: chip-well" /></a>&nbsp;&nbsp;<a href="https://github.com/GRAYAH"><img src="https:&#x2F;&#x2F;github.com&#x2F;GRAYAH.png" width="50px" alt="User avatar: GRAYAH" /></a>&nbsp;&nbsp;<a href="https://github.com/flashblaze"><img src="https:&#x2F;&#x2F;github.com&#x2F;flashblaze.png" width="50px" alt="User avatar: flashblaze" /></a>&nbsp;&nbsp;<a href="https://github.com/Frostist"><img src="https:&#x2F;&#x2F;github.com&#x2F;Frostist.png" width="50px" alt="User avatar: Frostist" /></a>&nbsp;&nbsp;<a href="https://github.com/PurplProto"><img src="https:&#x2F;&#x2F;github.com&#x2F;PurplProto.png" width="50px" alt="User avatar: PurplProto" /></a>&nbsp;&nbsp;<!-- sponsors-base -->
+180 -63
View File
@@ -1,9 +1,8 @@
import { linter } from "@codemirror/lint"; import { linter } from "@codemirror/lint";
import type { EditorView } from "@codemirror/view"; import type { EditorView } from "@codemirror/view";
import { jsoncLanguage } from "@shopify/lang-jsonc"; import { jsoncLanguage } from "@shopify/lang-jsonc";
import type { GrpcRequest } from "@yaakapp-internal/models"; import { type GrpcRequest, patchModel } from "@yaakapp-internal/models";
import { FormattedError, InlineCode, VStack } from "@yaakapp-internal/ui"; import { Banner, FormattedError, Icon, InlineCode, VStack } from "@yaakapp-internal/ui";
import classNames from "classnames";
import { import {
handleRefresh, handleRefresh,
jsonCompletion, jsonCompletion,
@@ -11,12 +10,20 @@ import {
stateExtensions, stateExtensions,
updateSchema, updateSchema,
} from "codemirror-json-schema"; } from "codemirror-json-schema";
import type { JSONSchema7 } from "json-schema";
import type { ReactNode } from "react";
import { useCallback, useEffect, useMemo, useState } from "react"; import { useCallback, useEffect, useMemo, useState } from "react";
import type { ReflectResponseService } from "../hooks/useGrpc"; import type { ReflectResponseService } from "../hooks/useGrpc";
import { wasUpdatedExternally } from "../hooks/useRequestUpdateKey";
import { showAlert } from "../lib/alert"; import { showAlert } from "../lib/alert";
import { showConfirm } from "../lib/confirm";
import { showDialog } from "../lib/dialog"; import { showDialog } from "../lib/dialog";
import type { JsonSchema } from "../lib/jsonSchemaExample";
import { buildExampleFromSchema } from "../lib/jsonSchemaExample";
import { pluralizeCount } from "../lib/pluralize"; import { pluralizeCount } from "../lib/pluralize";
import { queryClient } from "../lib/queryClient";
import { Button } from "./core/Button"; import { Button } from "./core/Button";
import { Dropdown } from "./core/Dropdown";
import type { EditorProps } from "./core/Editor/Editor"; import type { EditorProps } from "./core/Editor/Editor";
import { Editor } from "./core/Editor/LazyEditor"; import { Editor } from "./core/Editor/LazyEditor";
import { GrpcProtoSelectionDialog } from "./GrpcProtoSelectionDialog"; import { GrpcProtoSelectionDialog } from "./GrpcProtoSelectionDialog";
@@ -29,6 +36,11 @@ type Props = Pick<EditorProps, "heightMode" | "onChange" | "className" | "forceU
protoFiles: string[]; protoFiles: string[];
}; };
type MethodSchema =
| { type: "none" }
| { type: "schema"; schema: JsonSchema }
| { type: "error"; id: string; title: string; body: ReactNode; log: unknown[] };
export function GrpcEditor({ export function GrpcEditor({
services, services,
reflectionError, reflectionError,
@@ -42,21 +54,16 @@ export function GrpcEditor({
setEditorView(h); setEditorView(h);
}, []); }, []);
// Find the schema for the selected service and method and update the editor // Find the schema for the selected service and method
useEffect(() => { const methodSchema = useMemo<MethodSchema>(() => {
if ( if (services === null || request.service === null || request.method === null) {
editorView == null || return { type: "none" };
services === null ||
request.service === null ||
request.method === null
) {
return;
} }
const s = services.find((s) => s.name === request.service); const s = services.find((s) => s.name === request.service);
if (s == null) { if (s == null) {
console.log("Failed to find service", { service: request.service, services }); return {
showAlert({ type: "error",
id: "grpc-find-service-error", id: "grpc-find-service-error",
title: "Couldn't Find Service", title: "Couldn't Find Service",
body: ( body: (
@@ -64,14 +71,14 @@ export function GrpcEditor({
Failed to find service <InlineCode>{request.service}</InlineCode> in schema Failed to find service <InlineCode>{request.service}</InlineCode> in schema
</> </>
), ),
}); log: ["Failed to find service", { service: request.service, services }],
return; };
} }
const schema = s.methods.find((m) => m.name === request.method)?.schema; const schema = s.methods.find((m) => m.name === request.method)?.schema;
if (request.method != null && schema == null) { if (schema == null) {
console.log("Failed to find method", { method: request.method, methods: s?.methods }); return {
showAlert({ type: "error",
id: "grpc-find-schema-error", id: "grpc-find-schema-error",
title: "Couldn't Find Method", title: "Couldn't Find Method",
body: ( body: (
@@ -80,18 +87,15 @@ export function GrpcEditor({
<InlineCode>{request.service}</InlineCode> in schema <InlineCode>{request.service}</InlineCode> in schema
</> </>
), ),
}); log: ["Failed to find method", { method: request.method, methods: s.methods }],
return; };
}
if (schema == null) {
return;
} }
try { try {
updateSchema(editorView, JSON.parse(schema)); return { type: "schema", schema: JSON.parse(schema) as JsonSchema };
} catch (err) { } catch (err) {
showAlert({ return {
type: "error",
id: "grpc-parse-schema-error", id: "grpc-parse-schema-error",
title: "Failed to Parse Schema", title: "Failed to Parse Schema",
body: ( body: (
@@ -103,9 +107,22 @@ export function GrpcEditor({
<FormattedError>{String(err)}</FormattedError> <FormattedError>{String(err)}</FormattedError>
</VStack> </VStack>
), ),
}); log: ["Failed to parse schema", err],
};
} }
}, [editorView, services, request.method, request.service]); }, [services, request.method, request.service]);
useEffect(() => {
if (methodSchema.type !== "error") return;
console.log(...methodSchema.log);
showAlert({ id: methodSchema.id, title: methodSchema.title, body: methodSchema.body });
}, [methodSchema]);
// Update the editor whenever the schema changes
useEffect(() => {
if (editorView == null || methodSchema.type !== "schema") return;
updateSchema(editorView, methodSchema.schema as JSONSchema7);
}, [editorView, methodSchema]);
const extraExtensions = useMemo( const extraExtensions = useMemo(
() => [ () => [
@@ -124,45 +141,145 @@ export function GrpcEditor({
const reflectionUnavailable = reflectionError?.match(/unimplemented/i); const reflectionUnavailable = reflectionError?.match(/unimplemented/i);
reflectionError = reflectionUnavailable ? undefined : reflectionError; reflectionError = reflectionUnavailable ? undefined : reflectionError;
const handleGenerateExample = useCallback(async () => {
if (methodSchema.type !== "schema") return;
if (request.message.trim() !== "") {
const confirmed = await showConfirm({
id: "grpc-generate-example",
title: "Generate Example",
description: "The current message will be replaced with an example.",
confirmText: "Generate",
});
if (!confirmed) return;
}
const message = JSON.stringify(buildExampleFromSchema(methodSchema.schema), null, 2);
await patchModel(request, { message });
// Force the editor to pick up the new message
wasUpdatedExternally(request.id);
}, [methodSchema, request]);
// The reflect query is keyed by request, url and proto files, so a prefix invalidate
// reaches it without threading a refetch down from the connection layout.
const handleReloadSchema = useCallback(
() => queryClient.invalidateQueries({ queryKey: ["grpc_reflect", request.id] }),
[request.id],
);
const handleShowReflectionError = useCallback(() => {
showDialog({
id: "grpc-reflection-error",
title: "Reflection Failed",
size: "sm",
render: ({ hide }) => (
<>
<FormattedError>{reflectionError ?? "unknown"}</FormattedError>
<div className="w-full my-4">
<Button
className="ml-auto"
color="primary"
size="sm"
onClick={async () => {
hide();
await handleReloadSchema();
}}
>
Retry
</Button>
</div>
</>
),
});
}, [handleReloadSchema, reflectionError]);
const actions = useMemo( const actions = useMemo(
() => [ () => [
<div key="reflection" className={classNames(services == null && "opacity-100!")}> // Matches the GraphQL editor: one always-visible control labelled by schema state,
<Button // with everything schema-related behind it.
size="xs" <div key="schema" className="opacity-100!">
color={ <Dropdown
reflectionLoading items={[
? "secondary" {
: reflectionUnavailable // Hidden for servers without reflection, which isn't an error
? "info" hidden: !reflectionError,
: reflectionError type: "content",
? "danger" label: (
: "secondary" <Banner color="danger">
} <p className="mb-1">Reflection failed</p>
isLoading={reflectionLoading} <Button
onClick={() => { size="xs"
showDialog({ color="danger"
title: "Configure Schema", variant="border"
size: "md", onClick={handleShowReflectionError}
id: "reflection-failed", >
render: ({ hide }) => <GrpcProtoSelectionDialog onDone={hide} />, View Error
}); </Button>
}} </Banner>
),
},
{
label: "Generate Example Message",
leftSlot: <Icon icon="magic_wand" />,
disabled: methodSchema.type !== "schema",
onSelect: handleGenerateExample,
},
{ type: "separator" },
{
label: "Reload Schema",
leftSlot: <Icon icon="refresh" spin={reflectionLoading} />,
keepOpenOnSelect: true,
onSelect: handleReloadSchema,
},
{
label: protoFiles.length > 0 ? "Select Proto Files\u2026" : "Configure Schema\u2026",
leftSlot: <Icon icon="settings" />,
onSelect: () => {
showDialog({
title: "Configure Schema",
size: "md",
id: "grpc-configure-schema",
render: ({ hide }) => <GrpcProtoSelectionDialog onDone={hide} />,
});
},
},
]}
> >
{reflectionLoading <Button
? "Inspecting Schema" size="sm"
: reflectionUnavailable variant="border"
? "Select Proto Files" title="Schema"
: reflectionError forDropdown
? "Server Error" isLoading={reflectionLoading}
: protoFiles.length > 0 color={reflectionUnavailable ? "info" : reflectionError ? "danger" : "default"}
? pluralizeCount("File", protoFiles.length) >
: services != null && protoFiles.length === 0 {reflectionLoading
? "Schema Detected" ? "Inspecting Schema"
: "Select Schema"} : reflectionUnavailable
</Button> ? "Select Proto Files"
: reflectionError
? "Server Error"
: protoFiles.length > 0
? pluralizeCount("File", protoFiles.length)
: services != null
? "Schema Detected"
: "Select Schema"}
</Button>
</Dropdown>
</div>, </div>,
], ],
[protoFiles.length, reflectionError, reflectionLoading, reflectionUnavailable, services], [
handleGenerateExample,
handleReloadSchema,
handleShowReflectionError,
methodSchema.type,
protoFiles.length,
reflectionError,
reflectionLoading,
reflectionUnavailable,
services,
],
); );
return ( return (
@@ -194,13 +194,6 @@ export function GrpcRequestPane({
type: "default", type: "default",
shortLabel: o.label, shortLabel: o.label,
}))} }))}
itemsAfter={[
{
label: "Refresh",
type: "default",
leftSlot: <Icon size="sm" icon="refresh" />,
},
]}
> >
<Button <Button
size="sm" size="sm"
+681 -25
View File
@@ -1,15 +1,38 @@
import {
type Folder,
type ImportDestination,
type ImportPlan,
type ImportPlanItem,
type ImportSource,
type Workspace,
} from "@yaakapp-internal/models";
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 { Icon, VStack } from "@yaakapp-internal/ui";
import classNames from "classnames"; import classNames from "classnames";
import { useEffect, useRef, useState } from "react"; import { formatDistanceToNowStrict } from "date-fns";
import { useLocalStorage } from "react-use"; import { useEffect, useMemo, useRef, useState } from "react";
import { pluralize } from "../lib/pluralize";
import { CommercialUseBanner } from "./CommercialUseBanner"; import { CommercialUseBanner } from "./CommercialUseBanner";
import { Button } from "./core/Button"; import { Button } from "./core/Button";
import { Checkbox } from "./core/Checkbox";
import type { CheckboxTreeNode } from "./core/CheckboxTree";
import { CheckboxTree } from "./core/CheckboxTree";
import { IconTooltip } from "./core/IconTooltip";
import { PlainInput } from "./core/PlainInput"; import { PlainInput } from "./core/PlainInput";
import { Select } from "./core/Select";
import { SegmentedControl } from "./core/SegmentedControl";
interface Props { interface Props {
importFile: (filePath: string) => Promise<void>; currentWorkspace: Workspace | null;
importUrl: (url: string) => Promise<void>; workspaces: Workspace[];
selectedFolder: Folder | null;
planFile: (filePath: string, destination: ImportDestination) => Promise<ImportPlan>;
planUrl: (url: string, destination: ImportDestination) => Promise<ImportPlan>;
listSources: (workspaceId: string) => Promise<ImportSource[]>;
findSourcesForOrigin: (args: { filePath?: string; url?: string }) => Promise<ImportSource[]>;
commit: (plan: ImportPlan) => Promise<void>;
cancel: () => void;
onError: (err: unknown) => void;
} }
/** /**
@@ -31,10 +54,74 @@ function fileName(path: string): string {
return path.split(/[/\\]/).at(-1) || path; return path.split(/[/\\]/).at(-1) || path;
} }
export function ImportDataDialog({ importFile, importUrl }: Props) { /**
* Loads the current workspace's linked sources before rendering the dialog, so the inner
* component can construct its initial state (prefilled path, destination) in one pass instead of
* patching it in with effects after the first paint.
*/
export function ImportDataDialog(props: Props) {
const [initialSources, setInitialSources] = useState<ImportSource[] | null>(null);
const { currentWorkspace, listSources } = props;
useEffect(() => {
let cancelled = false;
const load = currentWorkspace == null ? Promise.resolve([]) : listSources(currentWorkspace.id);
load
.then((sources) => {
if (!cancelled) setInitialSources(sources);
})
.catch(() => {
if (!cancelled) setInitialSources([]);
});
return () => {
cancelled = true;
};
}, [currentWorkspace, listSources]);
if (initialSources == null) return null;
return <LoadedImportDataDialog {...props} initialSources={initialSources} />;
}
function latestSource(sources: ImportSource[]): ImportSource | null {
return sources.reduce<ImportSource | null>(
(latest, s) => (latest == null || s.lastImportedAt > latest.lastImportedAt ? s : latest),
null,
);
}
function LoadedImportDataDialog({
currentWorkspace,
workspaces,
selectedFolder,
planFile,
planUrl,
listSources,
findSourcesForOrigin,
commit,
cancel,
onError,
initialSources,
}: Props & { initialSources: ImportSource[] }) {
// A workspace with a linked source is probably being re-imported, so start from that source
const prefill = latestSource(initialSources);
const [isLoading, setIsLoading] = useState<boolean>(false); const [isLoading, setIsLoading] = useState<boolean>(false);
const [plan, setPlan] = useState<ImportPlan | null>(null);
const [items, setItems] = useState<ImportPlanItem[]>([]);
// null means no explicit choice yet, so the default below applies
const [destinationChoice, setDestinationChoice] = useState<"new" | "current" | "other" | null>(
null,
);
const [otherWorkspaceId, setOtherWorkspaceId] = useState<string | null>(null);
const [targetSelectedFolder, setTargetSelectedFolder] = useState(selectedFolder != null);
const [linkedSources, setLinkedSources] = useState<ImportSource[]>(
prefill != null ? initialSources : [],
);
const [originSources, setOriginSources] = useState<ImportSource[]>(
prefill != null ? [prefill] : [],
);
// A file path or a URL. Both inputs write here, so there is only ever one thing to import // A file path or a URL. Both inputs write here, so there is only ever one thing to import
const [source, setSource] = useLocalStorage<string | null>("importPathOrUrl", null); const [source, setSource] = useState<string | null>(prefill?.origin ?? null);
const [forceUpdateKey, setForceUpdateKey] = useState<number>(0); const [forceUpdateKey, setForceUpdateKey] = useState<number>(0);
const [isHovering, setIsHovering] = useState<boolean>(false); const [isHovering, setIsHovering] = useState<boolean>(false);
const ref = useRef<HTMLDivElement>(null); const ref = useRef<HTMLDivElement>(null);
@@ -65,25 +152,272 @@ export function ImportDataDialog({ importFile, importUrl }: Props) {
}); });
}, [isHovering, setSource]); }, [isHovering, setSource]);
useEffect(() => {
if (trimmedSource === "") {
setOriginSources([]);
return;
}
let cancelled = false;
const timeout = setTimeout(() => {
findSourcesForOrigin(filePath != null ? { filePath } : { url: trimmedSource })
.then((sources) => {
if (!cancelled) setOriginSources(sources);
})
.catch(() => setOriginSources([]));
}, 300);
return () => {
cancelled = true;
clearTimeout(timeout);
};
}, [trimmedSource, filePath, findSourcesForOrigin]);
// The one workspace this file is linked to, if there is exactly one.
const linkedWorkspace = useMemo(() => {
const ids = [...new Set(originSources.map((s) => s.workspaceId))];
if (ids.length !== 1) return null;
return workspaces.find((w) => w.id === ids[0]) ?? null;
}, [originSources, workspaces]);
// A file linked to the current workspace defaults back into it, so re-importing doesn't
// accidentally create a duplicate workspace. A file linked elsewhere only gets a suggestion —
// silently targeting a workspace that is neither new nor current is too surprising. An
// explicit choice always wins.
const destinationKind =
destinationChoice ??
(linkedWorkspace != null && linkedWorkspace.id === currentWorkspace?.id ? "current" : "new");
const destinationWorkspaceId =
destinationKind === "current"
? (currentWorkspace?.id ?? null)
: destinationKind === "other"
? otherWorkspaceId
: null;
useEffect(() => {
if (destinationWorkspaceId == null) {
setLinkedSources([]);
return;
}
let cancelled = false;
listSources(destinationWorkspaceId)
.then((sources) => {
if (!cancelled) setLinkedSources(sources);
})
.catch(() => setLinkedSources([]));
return () => {
cancelled = true;
};
}, [destinationWorkspaceId, listSources]);
const handleSelectFile = async () => { const handleSelectFile = async () => {
const selected = await platform.dialog.open({ title: "Select File", multiple: false }); const selected = await platform.dialog.open({ title: "Select File", multiple: false });
if (selected == null) return; if (selected == null) return;
selectSource(selected); selectSource(selected);
}; };
const handleImport = async () => { // The selected folder belongs to the workspace being viewed, so it is only offerable when that
// is also the destination.
const canTargetSelectedFolder = selectedFolder != null && destinationKind === "current";
const destination = (): ImportDestination => {
if (destinationWorkspaceId == null) {
return { type: "new_workspace" };
}
return {
type: "existing_workspace",
workspaceId: destinationWorkspaceId,
folderId: canTargetSelectedFolder && targetSelectedFolder ? selectedFolder.id : undefined,
};
};
const handlePreview = async () => {
setIsLoading(true); setIsLoading(true);
try { try {
if (filePath != null) { const nextPlan =
await importFile(filePath); filePath != null
} else { ? await planFile(filePath, destination())
await importUrl(trimmedSource); : await planUrl(trimmedSource, destination());
} setPlan(nextPlan);
setItems(nextPlan.items);
} catch (err) {
onError(err);
} finally { } finally {
setIsLoading(false); setIsLoading(false);
} }
}; };
const handleCommit = async () => {
if (plan == null) return;
setIsLoading(true);
try {
await commit({ ...plan, items });
} catch (err) {
onError(err);
} finally {
setIsLoading(false);
}
};
const itemTree = useMemo(() => buildItemTree(items), [items]);
// A folder row's checkbox carries everything beneath it, deletions included — the row labels
// say which of those are destructive. Checking anything also brings back the folders it needs
// to live in.
const toggleNode = (node: CheckboxTreeNode<TreeRow>, checked: boolean) => {
const targets = new Set(togglableItems(node).map((i) => i.modelId));
if (checked && node.data.kind === "item") {
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)));
};
const resolveConflict = (modelId: string, resolution: "keep_mine" | "take_source") => {
setItems((prev) =>
prev.map((item) => (item.modelId === modelId ? { ...item, resolution } : item)),
);
};
// Deleting a folder takes its contents with it, so those rows have nothing left to decide.
const disabledIds = useMemo(() => {
const disabled = new Set<string>();
const byId = new Map(items.map((i) => [i.modelId, i]));
for (const item of items) {
if (item.action !== "delete") continue;
for (const parent of ancestorsOf(item, byId)) {
if (parent.action === "delete" && parent.selected) {
disabled.add(item.modelId);
}
}
}
return disabled;
}, [items]);
if (plan != null) {
const unchanged = items.filter((i) => i.action === "unchanged");
const footerNote =
unchanged.length > 0
? `${unchanged.length} ${pluralize("resource", unchanged.length)} unchanged`
: "";
const changeCount = items.filter((item) => {
if (disabledIds.has(item.modelId)) return false;
if (item.action === "conflict") return item.resolution === "take_source";
if (item.action === "unchanged") return false;
return item.selected;
}).length;
// The row's label carries what kind of destination it is, so the value can just be its name
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 name = workspaces.find((w) => w.id === workspaceId)?.name ?? "Unknown workspace";
return [
"Destination",
folderId != null && folderId === selectedFolder?.id
? `${name} / ${selectedFolder.name}`
: name,
];
})();
// The destination workspace roots the tree. It is not a plan item — commit always applies
// it — so its checkbox only aggregates the subtree.
const workspaceRoot: CheckboxTreeNode<TreeRow> = (() => {
const planned = plan.resources.workspaces[0];
const planDestination = plan.destination;
const existing =
planDestination.type === "existing_workspace"
? workspaces.find((w) => w.id === planDestination.workspaceId)
: null;
return {
key: existing?.id ?? planned?.id ?? "workspace",
data: {
kind: "destination",
label: existing?.name ?? planned?.name ?? "New workspace",
isNew: planDestination.type === "new_workspace",
},
children: itemTree,
};
})();
return (
<VStack space={4} className="pb-4">
<div className="rounded-lg border border-border-subtle divide-y divide-border-subtle">
<PreviewRow label="Detected format" value={plan.importer} />
<PreviewRow label={destinationLabel} value={destinationValue} />
</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]">
<CheckboxTree
node={workspaceRoot}
checked={nodeCheckedStatus}
onCheck={toggleNode}
isCheckboxDisabled={(n) => disabledIds.has(n.key)}
isCollapsedByDefault={(n) => n.data.kind === "item" && n.data.item.action === "ignored"}
isRelevant={(n) =>
n.data.kind === "destination" ||
(n.data.kind === "item" && n.data.item.action !== "unchanged")
}
renderRow={(n) => <ImportTreeRow row={n.data} onResolveConflict={resolveConflict} />}
/>
</div>
<HStack space={2} alignItems="center" className="mt-3">
{footerNote !== "" && <div className="text-xs text-text-subtle">{footerNote}</div>}
<Button
className="ml-auto"
color="secondary"
variant="border"
disabled={isLoading}
onClick={() => {
setPlan(null);
setItems([]);
}}
>
Back
</Button>
<Button color="primary" isLoading={isLoading} onClick={handleCommit}>
{isLoading
? "Importing"
: changeCount > 0
? `Apply ${changeCount} ${changeCount === 1 ? "Change" : "Changes"}`
: "Done"}
</Button>
</HStack>
</VStack>
);
}
const lastImported =
originSources.find((s) => s.workspaceId === destinationWorkspaceId) ??
linkedSources.reduce<ImportSource | null>(
(latest, s) => (latest == null || s.lastImportedAt > latest.lastImportedAt ? s : latest),
null,
);
return ( return (
<VStack ref={ref} space={4} className="pb-4"> <VStack ref={ref} space={4} className="pb-4">
<CommercialUseBanner source="data-import" title="Importing work data?" /> <CommercialUseBanner source="data-import" title="Importing work data?" />
@@ -94,7 +428,9 @@ export function ImportDataDialog({ importFile, importUrl }: Props) {
className={classNames( className={classNames(
"w-full rounded-lg border border-dashed px-4 py-6", "w-full rounded-lg border border-dashed px-4 py-6",
"flex flex-col items-center gap-1 text-center", "flex flex-col items-center gap-1 text-center",
isHovering ? "border-notice bg-surface-highlight" : "border-border hover:border-text", isHovering
? "border-notice bg-surface-highlight"
: "border-border hover:border-text-subtle",
)} )}
> >
<Icon icon="folder_input" className="text-text-subtlest w-8! h-8! mb-2" /> <Icon icon="folder_input" className="text-text-subtlest w-8! h-8! mb-2" />
@@ -115,25 +451,345 @@ export function ImportDataDialog({ importFile, importUrl }: Props) {
</div> </div>
</button> </button>
<PlainInput
label="Or enter a file path or URL"
size="sm"
placeholder="https://example.com/openapi.json"
defaultValue={source ?? ""}
forceUpdateKey={String(forceUpdateKey)}
onChange={setSource}
/>
<VStack space={2}> <VStack space={2}>
<PlainInput <Select
label="Or enter a file path or URL" name="import-destination-kind"
label="Import location"
size="sm" size="sm"
placeholder="https://example.com/openapi.json" value={destinationKind}
defaultValue={source ?? ""} onChange={setDestinationChoice}
forceUpdateKey={String(forceUpdateKey)} options={[
onChange={setSource} { value: "new", label: "New Workspace" },
...(currentWorkspace != null
? [{ value: "current" as const, label: "Current Workspace" }]
: []),
{ value: "other", label: "Other Workspace" },
]}
/> />
{destinationKind === "other" && (
<Select
name="import-destination-workspace"
label="Workspace"
hideLabel
size="sm"
value={otherWorkspaceId ?? ""}
onChange={(id) => setOtherWorkspaceId(id === "" ? null : id)}
filterable
options={[
{ value: "", label: "Select a workspace" },
...workspaces
.filter((w) => w.id !== currentWorkspace?.id)
.map((w) => ({ value: w.id, label: w.name })),
]}
/>
)}
{lastImported != null && destinationWorkspaceId != null ? (
<div className="text-xs text-text-subtle">
Last imported from {lastImported.originLabel} ·{" "}
{formatDistanceToNowStrict(`${lastImported.lastImportedAt}Z`, { addSuffix: true })}
</div>
) : linkedWorkspace != null && linkedWorkspace.id !== destinationWorkspaceId ? (
<div className="text-xs text-text-subtle">
This file was last imported into{" "}
<button
type="button"
className="underline hocus:text-text"
onClick={() => {
if (linkedWorkspace.id === currentWorkspace?.id) {
setDestinationChoice("current");
} else {
setDestinationChoice("other");
setOtherWorkspaceId(linkedWorkspace.id);
}
}}
>
{linkedWorkspace.name}
</button>
</div>
) : null}
{canTargetSelectedFolder && (
<Checkbox
checked={targetSelectedFolder}
title={`Place root resources in selected folder “${selectedFolder.name}”`}
onChange={setTargetSelectedFolder}
/>
)}
</VStack>
<HStack space={2} justifyContent="end">
<Button color="secondary" variant="border" disabled={isLoading} onClick={cancel}>
Cancel
</Button>
<Button <Button
color="primary" color="primary"
disabled={trimmedSource === "" || isLoading} disabled={
trimmedSource === "" ||
isLoading ||
(destinationKind === "other" && otherWorkspaceId == null)
}
isLoading={isLoading} isLoading={isLoading}
size="sm" onClick={handlePreview}
onClick={handleImport}
> >
{isLoading ? "Importing" : "Import"} {isLoading ? "Analyzing" : "Preview Import"}
</Button> </Button>
</VStack> </HStack>
</VStack> </VStack>
); );
} }
function ImportTreeRow({
row,
onResolveConflict,
}: {
row: TreeRow;
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 (
<>
{item.model === "folder" || item.model === "environment" ? (
<Icon color="secondary" icon={item.model === "folder" ? "folder" : "variable"} />
) : (
<span aria-hidden className="w-4" />
)}
<div className="truncate flex-1">{item.name}</div>
{item.action === "conflict" ? (
<div className="shrink-0">
<SegmentedControl
name={`conflict-${item.modelId}`}
label={`Resolve conflict for ${item.name}`}
hideLabel
size="2xs"
help={actionHelp(item)}
value={item.resolution ?? "keep_mine"}
onChange={(v) => onResolveConflict(item.modelId, v)}
options={[
{ value: "keep_mine", label: "Keep mine" },
{ value: "take_source", label: "Take source" },
]}
/>
</div>
) : (
label != null && (
<ActionChip
label={label}
help={actionHelp(item)}
className={classNames(
item.action === "create" && "text-success",
item.action === "update" && "text-info",
item.action === "delete" && "text-danger",
item.action === "keep_local" && item.selected && "text-warning",
item.action === "ignored" && "text-text-subtlest",
)}
/>
)
)}
</>
);
}
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 {
switch (item.action) {
case "create":
return "new";
case "update":
return "updated";
case "delete":
return "removed";
case "keep_local":
return "edited";
case "ignored":
return "ignored";
default:
return 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) {
case "create":
return "Not in this workspace yet";
case "update":
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":
return "Gone from the source since the last import. Checking it deletes it here";
case "keep_local":
return help("Changed here since the last import. Checking it reverts to the source");
case "conflict":
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:
return null;
}
}
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 childrenOf = new Map<string, ImportPlanItem[]>();
const roots: ImportPlanItem[] = [];
for (const item of items) {
if (item.parentId != null && byId.has(item.parentId)) {
const siblings = childrenOf.get(item.parentId) ?? [];
siblings.push(item);
childrenOf.set(item.parentId, siblings);
} else {
roots.push(item);
}
}
const byKind = (list: ImportPlanItem[]) => [
...list.filter((i) => i.model === "environment"),
...list.filter((i) => i.model === "folder"),
...list.filter((i) => i.model !== "environment" && i.model !== "folder"),
];
const toNode = (item: ImportPlanItem, seen: Set<string>): CheckboxTreeNode<TreeRow> => ({
key: item.modelId,
data: { kind: "item", item },
children: seen.has(item.modelId)
? []
: byKind(childrenOf.get(item.modelId) ?? []).map((c) =>
toNode(c, new Set([...seen, item.modelId])),
),
});
// 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 collectRows(node: CheckboxTreeNode<TreeRow>): TreeRow[] {
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");
}
/**
* The plan item a row's checkbox decides, if it decides one. An unchanged resource has nothing to
* decide and a conflict is decided by its own control, so neither takes a checkbox — nor rides
* along with a parent's.
*/
function togglableItem(row: TreeRow): ImportPlanItem | null {
if (row.kind !== "item") return null;
const { item } = row;
return item.action === "unchanged" || item.action === "conflict" ? null : item;
}
function togglableItems(node: CheckboxTreeNode<TreeRow>): ImportPlanItem[] {
return collectRows(node)
.map(togglableItem)
.filter((i) => i != null);
}
function nodeCheckedStatus(node: CheckboxTreeNode<TreeRow>): boolean | "indeterminate" | "hidden" {
const covered = togglableItems(node);
if (covered.length === 0) return "hidden";
const selected = covered.filter((i) => i.selected).length;
if (selected === covered.length) return true;
if (selected === 0) return false;
return "indeterminate";
}
function PreviewRow({ label, value }: { label: string; value: string }) {
return (
<div className="flex items-start justify-between gap-4 px-3 py-2 text-sm">
<span className="text-text-subtle">{label}</span>
<span className="text-right font-medium">{value}</span>
</div>
);
}
@@ -0,0 +1,114 @@
import { Icon } from "@yaakapp-internal/ui";
import classNames from "classnames";
import type { ReactNode } from "react";
import { useState } from "react";
import type { CheckboxProps } from "./Checkbox";
import { Checkbox } from "./Checkbox";
export interface CheckboxTreeNode<T> {
key: string;
data: T;
children: CheckboxTreeNode<T>[];
}
interface Props<T> {
node: CheckboxTreeNode<T>;
depth?: number;
/** Return "hidden" to render row alignment space instead of a checkbox */
checked: (node: CheckboxTreeNode<T>) => CheckboxProps["checked"] | "hidden";
onCheck: (node: CheckboxTreeNode<T>, checked: boolean) => void;
checkboxTitle?: (node: CheckboxTreeNode<T>) => string;
isCheckboxDisabled?: (node: CheckboxTreeNode<T>) => boolean;
/** An irrelevant row is hidden unless one of its descendants is relevant */
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;
onSelectRow?: (node: CheckboxTreeNode<T>) => void;
canSelectRow?: (node: CheckboxTreeNode<T>) => boolean;
isRowSelected?: (node: CheckboxTreeNode<T>) => boolean;
}
export function CheckboxTree<T>(props: Props<T>) {
const { node, depth = 0 } = props;
const [collapsed, setCollapsed] = useState<boolean>(
() => props.isCollapsedByDefault?.(node) ?? false,
);
if (!hasRelevantNode(node, props.isRelevant)) return null;
const checked = props.checked(node);
const selected = props.isRowSelected?.(node) ?? false;
const selectable = props.onSelectRow != null && (props.canSelectRow?.(node) ?? true);
const hasVisibleChildren = node.children.some((c) => hasRelevantNode(c, props.isRelevant));
const rowContent = (
<div className="flex-1 min-w-0 flex items-center gap-1 px-1 py-0.5 text-left">
{props.renderRow(node)}
</div>
);
return (
<div
className={classNames(
depth > 0 && "pl-4 ml-2 border-l border-dashed border-border-subtle relative",
)}
>
<div
className={classNames(
"relative flex gap-1 w-full h-xs items-center",
selected ? "text-text" : "text-text-subtle",
)}
>
{selected && (
<div className="absolute left-[-100vw] right-0 top-0 bottom-0 bg-surface-active opacity-30 -z-10" />
)}
{hasVisibleChildren ? (
<button
type="button"
aria-label={collapsed ? "Expand" : "Collapse"}
aria-expanded={!collapsed}
className="shrink-0 text-text-subtlest hocus:text-text"
onClick={() => setCollapsed((v) => !v)}
>
<Icon size="sm" icon={collapsed ? "chevron_right" : "chevron_down"} />
</button>
) : (
<span aria-hidden className="w-4 shrink-0" />
)}
{checked === "hidden" ? (
<span aria-hidden className="w-4 mr-0.5 shrink-0" />
) : (
<Checkbox
checked={checked}
title={props.checkboxTitle?.(node) ?? "Toggle"}
hideLabel
disabled={props.isCheckboxDisabled?.(node)}
onChange={(checked) => props.onCheck(node, checked)}
/>
)}
{selectable ? (
<button
type="button"
className="flex-1 min-w-0 flex text-left"
onClick={() => props.onSelectRow?.(node)}
>
{rowContent}
</button>
) : (
rowContent
)}
</div>
{!collapsed &&
node.children.map((child) => (
<CheckboxTree key={child.key} {...props} node={child} depth={depth + 1} />
))}
</div>
);
}
function hasRelevantNode<T>(
node: CheckboxTreeNode<T>,
isRelevant: (node: CheckboxTreeNode<T>) => boolean,
): boolean {
return isRelevant(node) || node.children.some((c) => hasRelevantNode(c, isRelevant));
}
+7 -5
View File
@@ -10,11 +10,13 @@ export interface DialogProps {
children: ReactNode; children: ReactNode;
open: boolean; open: boolean;
onClose?: () => void; onClose?: () => void;
disableBackdropClose?: boolean; /** Block dismissal from the backdrop, Escape key, and built-in close button. */
disableClose?: boolean;
title?: ReactNode; title?: ReactNode;
description?: ReactNode; description?: ReactNode;
className?: string; className?: string;
size?: DialogSize; size?: DialogSize;
/** Hide the built-in close button without changing backdrop or Escape behavior. */
hideX?: boolean; hideX?: boolean;
noPadding?: boolean; noPadding?: boolean;
noScroll?: boolean; noScroll?: boolean;
@@ -27,7 +29,7 @@ export function Dialog({
size = "full", size = "full",
open, open,
onClose, onClose,
disableBackdropClose, disableClose,
title, title,
description, description,
hideX, hideX,
@@ -42,7 +44,7 @@ export function Dialog({
); );
return ( return (
<Overlay open={open} onClose={disableBackdropClose ? undefined : onClose} portalName="dialog"> <Overlay open={open} onClose={disableClose ? undefined : onClose} portalName="dialog">
<div <div
role="dialog" role="dialog"
className={classNames( className={classNames(
@@ -58,7 +60,7 @@ export function Dialog({
// NOTE: We handle Escape on the element itself so that it doesn't close multiple // NOTE: We handle Escape on the element itself so that it doesn't close multiple
// dialogs and can be intercepted by children if needed. // dialogs and can be intercepted by children if needed.
if (e.key === "Escape") { if (e.key === "Escape") {
onClose?.(); if (!disableClose) onClose?.();
e.stopPropagation(); e.stopPropagation();
e.preventDefault(); e.preventDefault();
} }
@@ -110,7 +112,7 @@ export function Dialog({
</div> </div>
{/*Put close at the end so that it's the last thing to be tabbed to*/} {/*Put close at the end so that it's the last thing to be tabbed to*/}
{!hideX && ( {!disableClose && !hideX && (
<div className="ml-auto absolute right-1 top-1"> <div className="ml-auto absolute right-1 top-1">
<IconButton <IconButton
className="opacity-70 hover:opacity-100" className="opacity-70 hover:opacity-100"
@@ -601,6 +601,8 @@ function getExtensions({
EditorView.contentAttributes.of({ EditorView.contentAttributes.of({
autocapitalize: "off", autocapitalize: "off",
autocorrect: "off", autocorrect: "off",
// Keeps macOS Writing Tools from offering to write code for us
writingsuggestions: "false",
}), }),
EditorView.domEventHandlers({ EditorView.domEventHandlers({
focus: () => { focus: () => {
@@ -0,0 +1,202 @@
import { SearchQuery } from "@codemirror/search";
import { EditorState } from "@codemirror/state";
import { describe, expect, test } from "vite-plus/test";
import {
currentMatch,
literalSearch,
MAX_COUNT,
MatchCounter,
normalizeDoc,
normalizeSearch,
scanNormalized,
scanQuery,
} from "./searchMatchCount";
type QueryConfig = ConstructorParameters<typeof SearchQuery>[0];
const stateOf = (doc: string) => EditorState.create({ doc });
/**
* The matches the counter finds, having checked them against the search panel's own cursor.
*
* The cursor decides which ranges the editor highlights and which one `find next` lands on, so
* a count that doesn't agree with it is a wrong count, however fast it was to produce.
*/
function matchesOf(doc: string, config: QueryConfig) {
const state = stateOf(doc);
const query = new SearchQuery(config);
const matches = new MatchCounter().matches(state, query);
expect(matches).toEqual(scanQuery(state, query));
return matches;
}
const countOf = (doc: string, config: QueryConfig) => matchesOf(doc, config).length;
describe("counting", () => {
test("counts every match, whatever the case", () => {
expect(countOf("one Two three two", { search: "two" })).toBe(2);
expect(countOf("one Two three two", { search: "two", caseSensitive: true })).toBe(1);
});
test("skips matches overlapping an earlier one", () => {
expect(countOf("aaaaa", { search: "aa" })).toBe(2);
expect(countOf("ababa", { search: "aba" })).toBe(1);
});
test("treats a query as text, not as a pattern", () => {
expect(countOf("a.b axb", { search: "a.b" })).toBe(1);
});
test("unquotes escapes unless the query is literal", () => {
expect(countOf("one\ntwo\nthree", { search: "\\n" })).toBe(2);
expect(countOf("one\\ntwo", { search: "\\n", literal: true })).toBe(1);
});
test("counts regexp and whole word queries through the cursor", () => {
expect(literalSearch(new SearchQuery({ search: "a", regexp: true }))).toBe(null);
expect(literalSearch(new SearchQuery({ search: "a", wholeWord: true }))).toBe(null);
expect(countOf("a1 b2 c3", { search: "[a-z]\\d", regexp: true })).toBe(3);
expect(countOf("cat cats cat", { search: "cat", wholeWord: true })).toBe(2);
});
test("stops counting at the cap", () => {
expect(countOf("x".repeat(MAX_COUNT + 100), { search: "x" })).toBe(MAX_COUNT + 1);
});
test("reports where the matches are", () => {
expect(matchesOf("ab..ab", { search: "ab" })).toEqual([
{ from: 0, to: 2 },
{ from: 4, to: 6 },
]);
});
test("finds nothing to match with an empty needle", () => {
expect(scanNormalized(normalizeDoc("abc", false), "")).toEqual([]);
});
});
describe("normalization", () => {
test("finds what a character decomposes into", () => {
// The é is one character holding an `e`, and the match covers the whole of it
expect(matchesOf("café", { search: "e" })).toEqual([{ from: 3, to: 4 }]);
expect(matchesOf("file", { search: "fi" })).toEqual([{ from: 0, to: 1 }]);
expect(matchesOf("a…b", { search: "..." })).toEqual([{ from: 1, to: 2 }]);
expect(countOf("one two", { search: "one two" })).toBe(1);
expect(countOf("full width", { search: "full" })).toBe(1);
});
test("matches a decomposed query against composed text, and the reverse", () => {
expect(countOf("café", { search: "café" })).toBe(1);
expect(countOf("café", { search: "café" })).toBe(1);
expect(countOf("café", { search: "café" })).toBe(1);
});
test("keeps offsets straight after an expansion", () => {
expect(matchesOf("é.é.end", { search: "end" })).toEqual([{ from: 4, to: 7 }]);
expect(matchesOf("fififi stop", { search: "stop" })).toEqual([{ from: 4, to: 8 }]);
});
test("normalizes the query whole, the document by character", () => {
expect(normalizeSearch("CAFÉ", false)).toBe("café");
expect(normalizeSearch("CAFÉ", true)).toBe("CAFÉ");
// Whole-string NFKD would fold this to a final sigma, which the cursor never does
expect(normalizeDoc("ΟΔΟΣ", false).text).toBe("οδοσ");
});
test("leaves a document that normalizes to itself untouched", () => {
const { text, expansions } = normalizeDoc("plain 日本 🎉 text", false);
expect(text).toBe("plain 日本 🎉 text");
expect(expansions).toEqual([]);
});
});
describe("current match", () => {
const matches = [
{ from: 0, to: 2 },
{ from: 4, to: 6 },
{ from: 8, to: 10 },
];
test("counts from one, and reports 0 off a match", () => {
expect(currentMatch(matches, { from: 4, to: 6 })).toBe(2);
expect(currentMatch(matches, { from: 8, to: 10 })).toBe(3);
expect(currentMatch(matches, { from: 5, to: 5 })).toBe(2);
expect(currentMatch(matches, { from: 2, to: 3 })).toBe(0);
expect(currentMatch(matches, { from: 4, to: 7 })).toBe(0);
expect(currentMatch([], { from: 0, to: 0 })).toBe(0);
});
test("moving the selection doesn't scan again", () => {
const state = stateOf("a1 b2 c3");
const query = new SearchQuery({ search: "\\d", regexp: true });
const counter = new MatchCounter();
const found = counter.matches(state, query);
// The document a selection-only transaction leaves behind is the one already scanned
const moved = state.update({ selection: { anchor: 4, head: 5 } }).state;
expect(counter.matches(moved, query)).toBe(found);
expect(currentMatch(found, moved.selection.main)).toBe(2);
});
});
/**
* The mapping from normalized offsets back to document offsets is the part of this that can go
* quietly wrong, and only on input nobody thinks to write a case for. So generate the input.
*/
describe("against the cursor, on awkward text", () => {
const ALPHABET = [
..."abcABC .\\\n".split(""),
"é",
"é",
"fi",
"…",
" ",
"İ",
"Σ",
"ς",
"日",
"🎉",
"Ⅻ",
"f",
"①",
"́",
];
/** Seeded, so a failure is the same failure next run */
function random(seed: number) {
let state = seed;
return () => {
state = (state * 1664525 + 1013904223) >>> 0;
return state / 2 ** 32;
};
}
for (const caseSensitive of [false, true]) {
test(`agrees on every generated document (caseSensitive: ${caseSensitive})`, () => {
const next = random(caseSensitive ? 20260831 : 7);
for (let round = 0; round < 400; round++) {
const doc = Array.from(
{ length: 2 + Math.floor(next() * 60) },
() => ALPHABET[Math.floor(next() * ALPHABET.length)]!,
).join("");
// Half the queries are lifted out of the document, so matches are actually found
const start = Math.floor(next() * doc.length);
const search =
next() < 0.5
? doc.slice(start, start + 1 + Math.floor(next() * 3))
: Array.from(
{ length: 1 + Math.floor(next() * 2) },
() => ALPHABET[Math.floor(next() * ALPHABET.length)]!,
).join("");
if (search === "") continue;
const state = stateOf(doc);
const query = new SearchQuery({ search, caseSensitive });
const where = `doc=${JSON.stringify(doc)} search=${JSON.stringify(search)}`;
expect(new MatchCounter().matches(state, query), where).toEqual(scanQuery(state, query));
}
});
}
});
@@ -1,7 +1,232 @@
import { getSearchQuery, searchPanelOpen } from "@codemirror/search"; import { getSearchQuery, type SearchQuery, searchPanelOpen } from "@codemirror/search";
import type { Extension } from "@codemirror/state"; import type { EditorState, Extension, Text } from "@codemirror/state";
import { type EditorView, ViewPlugin, type ViewUpdate } from "@codemirror/view"; import { type EditorView, ViewPlugin, type ViewUpdate } from "@codemirror/view";
/** Matches are counted no further than this, since an exact total stops being useful long before */
export const MAX_COUNT = 9999;
/** What normalizing rewrites: anything outside ASCII, plus the case it folds */
const REWRITTEN = /\P{ASCII}|[A-Z]+/gu;
const REWRITTEN_CASE_SENSITIVE = /\P{ASCII}/gu;
export interface Match {
from: number;
to: number;
}
/** A character whose normalized form is a different length, shifting every offset past it */
interface Expansion {
normFrom: number;
normTo: number;
docFrom: number;
docTo: number;
}
/** A document as SearchCursor compares it, with what's needed to get back to real offsets */
export interface NormalizedDoc {
text: string;
expansions: Expansion[];
}
/**
* Rewrites a document the way SearchCursor does — NFKD, then a case fold unless the search is
* case-sensitive — in a single pass rather than one call per code point.
*
* The cursor spends 90% of its time asking ICU about one character at a time, which is what
* makes counting matches in a large response slow. Doing it a character at a time still matters
* for the result, since it keeps NFKD from reordering marks across characters, so the
* granularity stays and only the repeated work goes: each distinct character is normalized once
* and the answer reused, and ASCII runs never reach ICU at all.
*/
export function normalizeDoc(text: string, caseSensitive: boolean): NormalizedDoc {
const rewritten = new Map<string, string>();
const expansions: Expansion[] = [];
let shift = 0;
const normalized = text.replace(
caseSensitive ? REWRITTEN_CASE_SENSITIVE : REWRITTEN,
(chunk: string, at: number) => {
// An ASCII run only ever folds case, which can't change its length
if (chunk.charCodeAt(0) < 0x80) return chunk.toLowerCase();
let out = rewritten.get(chunk);
if (out === undefined) {
out = chunk.normalize("NFKD");
if (!caseSensitive) out = out.toLowerCase();
rewritten.set(chunk, out);
}
if (out.length !== chunk.length) {
expansions.push({
normFrom: at + shift,
normTo: at + shift + out.length,
docFrom: at,
docTo: at + chunk.length,
});
shift += out.length - chunk.length;
}
return out;
},
);
return { text: normalized, expansions };
}
/** The query as SearchCursor compares it, which it normalizes whole rather than by character */
export function normalizeSearch(search: string, caseSensitive: boolean): string {
const normalized = search.normalize("NFKD");
return caseSensitive ? normalized : normalized.toLowerCase();
}
/** Every occurrence of `needle`, skipping matches that overlap an earlier one */
export function scanNormalized(doc: NormalizedDoc, needle: string): Match[] {
const matches: Match[] = [];
if (needle === "") return matches;
const { text } = doc;
let pos = text.indexOf(needle);
while (pos >= 0) {
let end = pos + needle.length;
// However the query was cut, a match ends on a whole code point, as the cursor's do
if (isLowSurrogate(text.charCodeAt(end))) end++;
matches.push({ from: docStart(doc, pos), to: docEnd(doc, end) });
if (matches.length > MAX_COUNT) break;
pos = text.indexOf(needle, resumeAfter(doc, end));
}
return matches;
}
/** The same through the query's own cursor, which handles regexps and whole words */
export function scanQuery(state: EditorState, query: SearchQuery): Match[] {
const matches: Match[] = [];
const cursor = query.getCursor(state);
for (let result = cursor.next(); !result.done; result = cursor.next()) {
matches.push({ from: result.value.from, to: result.value.to });
if (matches.length > MAX_COUNT) break;
}
return matches;
}
const isLowSurrogate = (code: number) => code >= 0xdc00 && code <= 0xdfff;
/** The last character expansion beginning at or before `offset`, if there is one */
function expansionAt({ expansions }: NormalizedDoc, offset: number): Expansion | null {
let low = 0;
let high = expansions.length - 1;
let found: Expansion | null = null;
while (low <= high) {
const mid = (low + high) >> 1;
if (expansions[mid]!.normFrom <= offset) {
found = expansions[mid]!;
low = mid + 1;
} else {
high = mid - 1;
}
}
return found;
}
function docStart(doc: NormalizedDoc, offset: number): number {
const expansion = expansionAt(doc, offset);
if (expansion == null) return offset;
// A match starting inside a character's expansion starts at the character
return offset < expansion.normTo
? expansion.docFrom
: offset - (expansion.normTo - expansion.docTo);
}
/**
* Where scanning picks up after a match ending at `offset`.
*
* The cursor moves through the document a character at a time, so once a match ends inside a
* character's expansion the rest of that expansion is behind it — "…" holds three dots but only
* ever counts as one match of ".".
*/
function resumeAfter(doc: NormalizedDoc, offset: number): number {
const expansion = expansionAt(doc, offset);
return expansion != null && offset > expansion.normFrom && offset < expansion.normTo
? expansion.normTo
: offset;
}
function docEnd(doc: NormalizedDoc, offset: number): number {
const expansion = expansionAt(doc, offset);
if (expansion == null) return offset;
if (offset <= expansion.normFrom) return expansion.docFrom;
// A match ending inside a character's expansion covers the whole character
return offset < expansion.normTo
? expansion.docTo
: offset - (expansion.normTo - expansion.docTo);
}
/** Position of the match holding the selection, counting from one, or 0 when it isn't on one */
export function currentMatch(matches: Match[], selection: { from: number; to: number }): number {
let index = 0;
for (const match of matches) {
index++;
if (match.from <= selection.from && match.to >= selection.to) return index;
}
return 0;
}
/** The text a plain query looks for, or null when only the cursor can answer it */
export function literalSearch(query: SearchQuery): string | null {
if (query.regexp || query.wholeWord || query.test != null) return null;
// Mirrors SearchQuery's own unquoting, which the published type doesn't expose
return query.literal
? query.search
: query.search.replace(/\\([nrt\\])/g, (_, ch) =>
ch === "n" ? "\n" : ch === "r" ? "\r" : ch === "t" ? "\t" : "\\",
);
}
/**
* Finds the matches for the search panel, keeping the normalized document and the matches it
* last found, so neither moving the selection nor typing another character starts over.
*/
export class MatchCounter {
private doc: { doc: Text; caseSensitive: boolean; normalized: NormalizedDoc } | null = null;
private last: { doc: Text; query: SearchQuery; matches: Match[] } | null = null;
matches(state: EditorState, query: SearchQuery): Match[] {
const last = this.last;
if (last != null && last.doc === state.doc && last.query.eq(query)) {
return last.matches;
}
const matches = this.scan(state, query);
this.last = { doc: state.doc, query, matches };
return matches;
}
private scan(state: EditorState, query: SearchQuery): Match[] {
const search = literalSearch(query);
if (search == null) return scanQuery(state, query);
const doc = this.normalizedDoc(state.doc, query.caseSensitive);
return scanNormalized(doc, normalizeSearch(search, query.caseSensitive));
}
private normalizedDoc(doc: Text, caseSensitive: boolean): NormalizedDoc {
const cached = this.doc;
if (cached != null && cached.doc === doc && cached.caseSensitive === caseSensitive) {
return cached.normalized;
}
const normalized = normalizeDoc(doc.toString(), caseSensitive);
this.doc = { doc, caseSensitive, normalized };
return normalized;
}
}
/** /**
* A CodeMirror extension that displays the total number of search matches * A CodeMirror extension that displays the total number of search matches
* inside the built-in search panel. * inside the built-in search panel.
@@ -10,6 +235,7 @@ export function searchMatchCount(): Extension {
return ViewPlugin.fromClass( return ViewPlugin.fromClass(
class { class {
private countEl: HTMLElement | null = null; private countEl: HTMLElement | null = null;
private counter = new MatchCounter();
constructor(private view: EditorView) { constructor(private view: EditorView) {
this.updateCount(); this.updateCount();
@@ -38,38 +264,21 @@ export function searchMatchCount(): Extension {
} }
this.ensureCountEl(); this.ensureCountEl();
if (this.countEl == null) return;
if (!query.search) { if (!query.search) {
if (this.countEl) { this.countEl.textContent = "0/0";
this.countEl.textContent = "0/0";
}
return; return;
} }
const selection = state.selection.main; const matches = this.counter.matches(state, query);
let count = 0; if (matches.length > MAX_COUNT) {
let currentIndex = 0; this.countEl.textContent = `${MAX_COUNT}+`;
const MAX_COUNT = 9999; } else if (matches.length === 0) {
const cursor = query.getCursor(state); this.countEl.textContent = "0/0";
for (let result = cursor.next(); !result.done; result = cursor.next()) { } else {
count++; const current = currentMatch(matches, state.selection.main);
const match = result.value; this.countEl.textContent = `${current}/${matches.length}`;
if (match.from <= selection.from && match.to >= selection.to) {
currentIndex = count;
}
if (count > MAX_COUNT) break;
}
if (this.countEl) {
if (count > MAX_COUNT) {
this.countEl.textContent = `${MAX_COUNT}+`;
} else if (count === 0) {
this.countEl.textContent = "0/0";
} else if (currentIndex > 0) {
this.countEl.textContent = `${currentIndex}/${count}`;
} else {
this.countEl.textContent = `0/${count}`;
}
} }
} }
@@ -113,7 +113,15 @@ function toPairData({ commitName: _commitName, ...pair }: EditablePairWithId): P
/** Max number of pairs to show before prompting the user to reveal the rest */ /** Max number of pairs to show before prompting the user to reveal the rest */
const MAX_INITIAL_PAIRS = 30; const MAX_INITIAL_PAIRS = 30;
export function PairEditor({ // Keyed on `stateKey` so no state survives a change of owner. Row ids alone can't tell owners
// apart — two pair sets can share ids (eg. one duplicated from the other), and the same-rows
// fast path below would swap in the new data without rebuilding the row editors, leaving any
// still-focused input showing the old owner's text.
export function PairEditor(props: PairEditorProps) {
return <PairEditorInner key={props.stateKey} {...props} />;
}
function PairEditorInner({
allowFileValues, allowFileValues,
allowMultilineValues, allowMultilineValues,
className, className,
@@ -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)}
/> />
); );
+6 -2
View File
@@ -119,9 +119,13 @@ export function Select<T extends string>({
)} )}
> >
<Button <Button
className="w-full text-sm font-mono" className={classNames(
"w-full text-sm font-mono",
disabled && "border-dotted",
isInvalidSelection && "border-danger",
)}
justify="start" justify="start"
variant="border" variant="input"
size={size} size={size}
leftSlot={leftSlot} leftSlot={leftSlot}
disabled={disabled} disabled={disabled}
@@ -21,6 +21,8 @@ import { CommercialUseBanner } from "../CommercialUseBanner";
import { Button } from "../core/Button"; import { Button } from "../core/Button";
import type { CheckboxProps } from "../core/Checkbox"; import type { CheckboxProps } from "../core/Checkbox";
import { Checkbox } from "../core/Checkbox"; import { Checkbox } from "../core/Checkbox";
import type { CheckboxTreeNode } from "../core/CheckboxTree";
import { CheckboxTree } from "../core/CheckboxTree";
import { DiffViewer } from "../core/Editor/DiffViewer"; import { DiffViewer } from "../core/Editor/DiffViewer";
import { Input } from "../core/Input"; import { Input } from "../core/Input";
import { Separator } from "../core/Separator"; import { Separator } from "../core/Separator";
@@ -43,10 +45,7 @@ interface CommitTreeNode {
export function GitCommitDialog({ syncDir, onDone, workspace }: Props) { export function GitCommitDialog({ syncDir, onDone, workspace }: Props) {
const callbacks = useGitCallbacks(syncDir); const callbacks = useGitCallbacks(syncDir);
const [{ status }, { commit, commitAndPush, add, unstage, restore }] = useGit( const [{ status }, { commit, commitAndPush, add, unstage, restore }] = useGit(syncDir, callbacks);
syncDir,
callbacks,
);
const [isPushing, setIsPushing] = useState(false); const [isPushing, setIsPushing] = useState(false);
const [commitError, setCommitError] = useState<string | null>(null); const [commitError, setCommitError] = useState<string | null>(null);
const [message, setMessage] = useState<string>(""); const [message, setMessage] = useState<string>("");
@@ -143,6 +142,15 @@ export function GitCommitDialog({ syncDir, onDone, workspace }: Props) {
return next(workspace, []); return next(workspace, []);
}, [workspace, internalEntries]); }, [workspace, internalEntries]);
const treeNode: CheckboxTreeNode<CommitTreeNode> | null = useMemo(() => {
const toTreeNode = (n: CommitTreeNode): CheckboxTreeNode<CommitTreeNode> => ({
key: n.status.relaPath + n.status.status + n.status.staged,
data: n,
children: n.children.map(toTreeNode),
});
return tree == null ? null : toTreeNode(tree);
}, [tree]);
const checkNode = useCallback( const checkNode = useCallback(
(treeNode: CommitTreeNode) => { (treeNode: CommitTreeNode) => {
const checked = nodeCheckedStatus(treeNode); const checked = nodeCheckedStatus(treeNode);
@@ -190,7 +198,7 @@ export function GitCommitDialog({ syncDir, onDone, workspace }: Props) {
[restore], [restore],
); );
if (tree == null) { if (tree == null || treeNode == null) {
return null; return null;
} }
@@ -221,12 +229,18 @@ export function GitCommitDialog({ syncDir, onDone, workspace }: Props) {
style={innerStyle} style={innerStyle}
className="h-full overflow-y-auto pb-3 pr-0.5 transform-cpu" className="h-full overflow-y-auto pb-3 pr-0.5 transform-cpu"
> >
<TreeNodeChildren <CheckboxTree
node={tree} node={treeNode}
depth={0} checked={(n) => nodeCheckedStatus(n.data)}
onCheck={checkNode} onCheck={(n) => checkNode(n.data)}
onSelect={handleSelectChild} checkboxTitle={(n) =>
selectedPath={selectedEntry?.relaPath ?? null} nodeCheckedStatus(n.data) ? "Unstage change" : "Stage change"
}
isRelevant={(n) => n.data.status.status !== "current"}
canSelectRow={(n) => n.data.status.status !== "current"}
onSelectRow={(n) => handleSelectChild(n.data.status)}
isRowSelected={(n) => selectedEntry?.relaPath === n.data.status.relaPath}
renderRow={(n) => <CommitTreeRow node={n.data} />}
/> />
{externalEntries.find((e) => e.status !== "current") && ( {externalEntries.find((e) => e.status !== "current") && (
<> <>
@@ -244,10 +258,7 @@ export function GitCommitDialog({ syncDir, onDone, workspace }: Props) {
</div> </div>
)} )}
secondSlot={({ style: innerStyle }) => ( secondSlot={({ style: innerStyle }) => (
<div <div style={innerStyle} className="grid grid-rows-[minmax(0,1fr)_auto] gap-3 pb-2">
style={innerStyle}
className="grid grid-rows-[minmax(0,1fr)_auto] gap-3 pb-2"
>
<Input <Input
className="text-base! font-sans rounded-md" className="text-base! font-sans rounded-md"
placeholder="Commit message..." placeholder="Commit message..."
@@ -301,96 +312,39 @@ export function GitCommitDialog({ syncDir, onDone, workspace }: Props) {
); );
} }
function TreeNodeChildren({ function CommitTreeRow({ node }: { node: CommitTreeNode }) {
node,
depth,
onCheck,
onSelect,
selectedPath,
}: {
node: CommitTreeNode | null;
depth: number;
onCheck: (node: CommitTreeNode, checked: boolean) => void;
onSelect: (entry: GitStatusEntry) => void;
selectedPath: string | null;
}) {
if (node === null) return null;
if (!isNodeRelevant(node)) return null;
const checked = nodeCheckedStatus(node);
const isSelected = selectedPath === node.status.relaPath;
return ( return (
<div <>
className={classNames( {node.model.model !== "http_request" &&
depth > 0 && "pl-4 ml-2 border-l border-dashed border-border-subtle relative", node.model.model !== "grpc_request" &&
)} node.model.model !== "websocket_request" ? (
> <Icon
<div color="secondary"
className={classNames( icon={
"relative flex gap-1 w-full h-xs items-center", node.model.model === "folder"
isSelected ? "text-text" : "text-text-subtle", ? "folder"
)} : node.model.model === "environment"
> ? "variable"
{isSelected && ( : "house"
<div className="absolute left-[-100vw] right-0 top-0 bottom-0 bg-surface-active opacity-30 -z-10" /> }
)}
<Checkbox
checked={checked}
title={checked ? "Unstage change" : "Stage change"}
hideLabel
onChange={(checked) => onCheck(node, checked)}
/> />
<button ) : (
type="button" <span aria-hidden className="w-4" />
className={classNames("flex-1 min-w-0 flex items-center gap-1 px-1 py-0.5 text-left")} )}
onClick={() => node.status.status !== "current" && onSelect(node.status)} <div className="truncate flex-1">{resolvedModelName(node.model)}</div>
{node.status.status !== "current" && (
<InlineCode
className={classNames(
"py-0 bg-transparent w-24 text-center shrink-0",
node.status.status === "modified" && "text-info",
node.status.status === "untracked" && "text-success",
node.status.status === "removed" && "text-danger",
)}
> >
{node.model.model !== "http_request" && {node.status.status}
node.model.model !== "grpc_request" && </InlineCode>
node.model.model !== "websocket_request" ? ( )}
<Icon </>
color="secondary"
icon={
node.model.model === "folder"
? "folder"
: node.model.model === "environment"
? "variable"
: "house"
}
/>
) : (
<span aria-hidden className="w-4" />
)}
<div className="truncate flex-1">{resolvedModelName(node.model)}</div>
{node.status.status !== "current" && (
<InlineCode
className={classNames(
"py-0 bg-transparent w-24 text-center shrink-0",
node.status.status === "modified" && "text-info",
node.status.status === "untracked" && "text-success",
node.status.status === "removed" && "text-danger",
)}
>
{node.status.status}
</InlineCode>
)}
</button>
</div>
{node.children.map((childNode) => {
return (
<TreeNodeChildren
key={childNode.status.relaPath + childNode.status.status + childNode.status.staged}
node={childNode}
depth={depth + 1}
onCheck={onCheck}
onSelect={onSelect}
selectedPath={selectedPath}
/>
);
})}
</div>
); );
} }
@@ -495,15 +449,6 @@ function setCheckedAndChildren(
if (toUnstage.length > 0) unstage({ relaPaths: toUnstage }); if (toUnstage.length > 0) unstage({ relaPaths: toUnstage });
} }
function isNodeRelevant(node: CommitTreeNode): boolean {
if (node.status.status !== "current") {
return true;
}
// Recursively check children
return node.children.some((c) => isNodeRelevant(c));
}
function DiffPanel({ function DiffPanel({
entry, entry,
onDiscardChanges, onDiscardChanges,
@@ -526,13 +471,11 @@ function DiffPanel({
size="2xs" size="2xs"
variant="border" variant="border"
onClick={() => onDiscardChanges(entry)} onClick={() => onDiscardChanges(entry)}
>Discard Changes</Button> >
Discard Changes
</Button>
</div> </div>
<DiffViewer <DiffViewer original={prevYaml ?? ""} modified={nextYaml ?? ""} className="flex-1 min-h-0" />
original={prevYaml ?? ""}
modified={nextYaml ?? ""}
className="flex-1 min-h-0"
/>
</div> </div>
); );
} }
+1 -3
View File
@@ -86,10 +86,8 @@ export async function promptDivergedStrategy({
showDialog({ showDialog({
id: "git-diverged", id: "git-diverged",
title: "Branches Diverged", title: "Branches Diverged",
hideX: true,
size: "sm", size: "sm",
disableBackdropClose: true, disableClose: true,
onClose: () => resolve("cancel"),
render: ({ hide }) => render: ({ hide }) =>
DivergedDialog({ DivergedDialog({
remote, remote,
+1 -2
View File
@@ -14,9 +14,8 @@ export function showAlert({ id, title, body, size = "sm" }: AlertArgs) {
showDialog({ showDialog({
id, id,
title, title,
hideX: true,
size, size,
disableBackdropClose: true, // Prevent accidental dismisses disableClose: true,
render: ({ hide }) => Alert({ onHide: hide, body }), render: ({ hide }) => Alert({ onHide: hide, body }),
}); });
} }
+1 -2
View File
@@ -18,9 +18,8 @@ export async function showConfirm({
return new Promise((onResult: ConfirmProps["onResult"]) => { return new Promise((onResult: ConfirmProps["onResult"]) => {
showDialog({ showDialog({
...extraProps, ...extraProps,
hideX: true,
size, size,
disableBackdropClose: true, // Prevent accidental dismisses disableClose: true,
render: ({ hide }) => Confirm({ onHide: hide, color, onResult, confirmText, requireTyping }), render: ({ hide }) => Confirm({ onHide: hide, color, onResult, confirmText, requireTyping }),
}); });
}); });
+49 -17
View File
@@ -1,14 +1,34 @@
import type { BatchUpsertResult } from "@yaakapp-internal/models"; import {
type BatchUpsertResult,
type ImportDestination,
type ImportPlan,
type ImportSource,
workspacesAtom,
} from "@yaakapp-internal/models";
import { FormattedError, VStack } from "@yaakapp-internal/ui"; import { FormattedError, VStack } from "@yaakapp-internal/ui";
import { Button } from "../components/core/Button"; import { Button } from "../components/core/Button";
import { ImportDataDialog } from "../components/ImportDataDialog"; import { ImportDataDialog } from "../components/ImportDataDialog";
import { activeFolderAtom } from "../hooks/useActiveFolder";
import { activeWorkspaceAtom } from "../hooks/useActiveWorkspace";
import { createFastMutation } from "../hooks/useFastMutation"; import { createFastMutation } from "../hooks/useFastMutation";
import { showAlert } from "./alert"; import { showAlert } from "./alert";
import { showDialog } from "./dialog"; import { showDialog } from "./dialog";
import { jotaiStore } from "./jotai";
import { pluralizeCount } from "./pluralize"; import { pluralizeCount } from "./pluralize";
import { router } from "./router"; import { router } from "./router";
import { rpc } from "./rpc"; import { rpc } from "./rpc";
// Stable identities so the dialog's effects don't re-run (and cancel in-flight
// fetches) every time the dialog container re-renders.
const planFile = (filePath: string, destination: ImportDestination) =>
rpc<ImportPlan>("cmd_import_data", { filePath, destination });
const planUrl = (url: string, destination: ImportDestination) =>
rpc<ImportPlan>("cmd_import_url", { url, destination });
const listSources = (workspaceId: string) =>
rpc<ImportSource[]>("cmd_list_import_sources", { workspaceId });
const findSourcesForOrigin = (args: { filePath?: string; url?: string }) =>
rpc<ImportSource[]>("cmd_import_sources_for_origin", args);
export const importData = createFastMutation({ export const importData = createFastMutation({
mutationKey: ["import_data"], mutationKey: ["import_data"],
onError: (err: string) => { onError: (err: string) => {
@@ -21,29 +41,41 @@ export const importData = createFastMutation({
}, },
mutationFn: async () => { mutationFn: async () => {
return new Promise<void>((resolve, reject) => { return new Promise<void>((resolve, reject) => {
const currentWorkspace = jotaiStore.get(activeWorkspaceAtom);
const workspaces = jotaiStore.get(workspacesAtom);
const selectedFolder = jotaiStore.get(activeFolderAtom);
showDialog({ showDialog({
id: "import", id: "import",
title: "Import Data", title: "Import Data",
size: "sm", size: "lg",
disableClose: true,
render: ({ hide }) => { render: ({ hide }) => {
const importAndHide = async (runImport: () => Promise<BatchUpsertResult>) => { const cancel = () => {
try { hide();
await finishImport(await runImport()); resolve();
resolve(); };
} catch (err) { const fail = (err: unknown) => {
reject(err); hide();
} finally { reject(err);
hide(); };
} const commit = async (plan: ImportPlan) => {
const imported = await rpc<BatchUpsertResult>("cmd_commit_import", { plan });
hide();
await finishImport(imported);
resolve();
}; };
return ( return (
<ImportDataDialog <ImportDataDialog
importFile={(filePath) => currentWorkspace={currentWorkspace}
importAndHide(() => rpc<BatchUpsertResult>("cmd_import_data", { filePath })) workspaces={workspaces}
} selectedFolder={selectedFolder}
importUrl={(url) => planFile={planFile}
importAndHide(() => rpc<BatchUpsertResult>("cmd_import_url", { url })) planUrl={planUrl}
} listSources={listSources}
findSourcesForOrigin={findSourcesForOrigin}
commit={commit}
cancel={cancel}
onError={fail}
/> />
); );
}, },
@@ -0,0 +1,251 @@
import { describe, expect, test } from "vite-plus/test";
import type { JsonSchema } from "./jsonSchemaExample";
import { buildExampleFromSchema } from "./jsonSchemaExample";
describe("buildExampleFromSchema", () => {
test("fills scalar fields with placeholders", () => {
const schema: JsonSchema = {
type: "object",
properties: {
name: { type: "string" },
age: { type: "number", format: "int32" },
active: { type: "boolean" },
data: { type: "string", format: "byte" },
},
};
expect(buildExampleFromSchema(schema)).toEqual({
name: "",
age: 0,
active: false,
data: "",
});
});
test("encodes 64-bit integers as strings", () => {
const schema: JsonSchema = {
type: "object",
properties: {
id: { type: "string", format: "int64" },
count: { type: "string", format: "uint64" },
offset: { type: "string", format: "sfixed64" },
},
};
expect(buildExampleFromSchema(schema)).toEqual({ id: "0", count: "0", offset: "0" });
});
test("fills date-time with a parseable timestamp", () => {
const schema: JsonSchema = {
type: "object",
properties: { createdAt: { type: "string", format: "date-time" } },
};
const example = buildExampleFromSchema(schema) as { createdAt: string };
expect(Number.isNaN(Date.parse(example.createdAt))).toBe(false);
});
test("fills a duration with a value that parses", () => {
const schema: JsonSchema = {
type: "object",
properties: { timeout: { type: "string", format: "duration" } },
};
// An empty string fails protobuf's Duration parsing, so the message wouldn't send
expect(buildExampleFromSchema(schema)).toEqual({ timeout: "0s" });
});
test("expands nested messages through $defs", () => {
const schema: JsonSchema = {
type: "object",
properties: { user: { $ref: "#/$defs/example.User" } },
$defs: {
"example.User": {
type: "object",
properties: {
name: { type: "string" },
address: { $ref: "#/$defs/example.Address" },
},
},
"example.Address": {
type: "object",
properties: { city: { type: "string" } },
},
},
};
expect(buildExampleFromSchema(schema)).toEqual({
user: { name: "", address: { city: "" } },
});
});
test("gives repeated fields a single placeholder item", () => {
const schema: JsonSchema = {
type: "object",
properties: {
tags: { type: "array", items: { type: "string" } },
users: { type: "array", items: { $ref: "#/$defs/example.User" } },
unknown: { type: "array" },
},
$defs: {
"example.User": { type: "object", properties: { name: { type: "string" } } },
},
};
expect(buildExampleFromSchema(schema)).toEqual({
tags: [""],
users: [{ name: "" }],
unknown: [],
});
});
test("uses the first value of an enum", () => {
const schema: JsonSchema = {
type: "object",
properties: {
status: { type: "string", enum: ["STATUS_UNSPECIFIED", "STATUS_ACTIVE"] },
empty: { type: "string", enum: [] },
},
};
expect(buildExampleFromSchema(schema)).toEqual({ status: "STATUS_UNSPECIFIED", empty: "" });
});
test("gives maps a single placeholder entry", () => {
const schema: JsonSchema = {
type: "object",
properties: {
labels: { type: "object", additionalProperties: { type: "string" } },
users: { type: "object", additionalProperties: { $ref: "#/$defs/example.User" } },
},
$defs: {
"example.User": { type: "object", properties: { name: { type: "string" } } },
},
};
expect(buildExampleFromSchema(schema)).toEqual({
labels: { key: "" },
users: { key: { name: "" } },
});
});
test("stops at the root self-reference", () => {
const schema: JsonSchema = {
type: "object",
properties: {
value: { type: "string" },
children: { type: "array", items: { $ref: "#" } },
},
};
expect(buildExampleFromSchema(schema)).toEqual({ value: "", children: [{}] });
});
test("stops at a cycle between messages", () => {
const schema: JsonSchema = {
type: "object",
properties: { node: { $ref: "#/$defs/example.Node" } },
$defs: {
"example.Node": {
type: "object",
properties: {
name: { type: "string" },
parent: { $ref: "#/$defs/example.Node" },
leaf: { $ref: "#/$defs/example.Leaf" },
},
},
"example.Leaf": {
type: "object",
properties: { node: { $ref: "#/$defs/example.Node" } },
},
},
};
expect(buildExampleFromSchema(schema)).toEqual({
node: { name: "", parent: {}, leaf: { node: {} } },
});
});
test("expands the same message twice when it is not on the same path", () => {
const schema: JsonSchema = {
type: "object",
properties: {
from: { $ref: "#/$defs/example.User" },
to: { $ref: "#/$defs/example.User" },
},
$defs: {
"example.User": { type: "object", properties: { name: { type: "string" } } },
},
};
expect(buildExampleFromSchema(schema)).toEqual({ from: { name: "" }, to: { name: "" } });
});
test("fills every branch of a flattened oneof", () => {
const schema: JsonSchema = {
type: "object",
properties: {
id: { type: "string" },
text: { type: "string" },
image: { $ref: "#/$defs/example.Image" },
},
$defs: {
"example.Image": { type: "object", properties: { url: { type: "string" } } },
},
};
expect(buildExampleFromSchema(schema)).toEqual({
id: "",
text: "",
image: { url: "" },
});
});
test("stops expanding once the node budget runs out", () => {
// Every level references the next one twice, so an unbounded walk would build 2^depth
// nodes without ever repeating a ref on the same path.
const depth = 16;
const $defs: Record<string, JsonSchema> = { [`d${depth}`]: { type: "string" } };
for (let i = 0; i < depth; i++) {
$defs[`d${i}`] = {
type: "object",
properties: {
a: { $ref: `#/$defs/d${i + 1}` },
b: { $ref: `#/$defs/d${i + 1}` },
},
};
}
const example = buildExampleFromSchema({
type: "object",
properties: { root: { $ref: "#/$defs/d0" } },
$defs,
});
// 2 ** 16 nodes unbounded; the budget holds it to a couple of thousand
expect(countNodes(example)).toBeLessThan(10_000);
});
test("handles messages without a known type", () => {
const schema: JsonSchema = {
type: "object",
properties: {
empty: {},
struct: { type: "object" },
missing: { $ref: "#/$defs/example.Nope" },
},
};
expect(buildExampleFromSchema(schema)).toEqual({ empty: null, struct: {}, missing: {} });
});
});
function countNodes(value: unknown): number {
if (Array.isArray(value)) {
return 1 + value.reduce((total: number, v) => total + countNodes(v), 0);
}
if (value !== null && typeof value === "object") {
return 1 + Object.values(value).reduce((total: number, v) => total + countNodes(v), 0);
}
return 1;
}
+121
View File
@@ -0,0 +1,121 @@
/**
* Subset of JSON Schema emitted by the gRPC reflection layer for a method's
* input message. See `message_to_json_schema` in the `yaak-grpc` crate.
*/
export type JsonSchema = {
type?: string;
format?: string;
properties?: Record<string, JsonSchema>;
items?: JsonSchema;
additionalProperties?: JsonSchema;
enum?: unknown[];
$defs?: Record<string, JsonSchema>;
$ref?: string;
};
const DEFS_PREFIX = "#/$defs/";
const ROOT_REF = "#";
// Protobuf 64-bit integers are encoded as strings in the JSON mapping
const STRING_NUMBER_FORMATS = ["int64", "uint64", "sint64", "fixed64", "sfixed64"];
// Refs on sibling branches each expand their own subtree, so a schema that references the
// same messages repeatedly can produce exponentially many nodes without ever cycling.
const MAX_NODES = 5000;
type Budget = { remaining: number };
/** Build a sample message with placeholder values for every field in the schema */
export function buildExampleFromSchema(schema: JsonSchema): unknown {
// The root is already being built, so a `#` ref anywhere below it is a cycle
return buildValue(schema, schema, new Set([ROOT_REF]), { remaining: MAX_NODES });
}
function buildValue(
schema: JsonSchema,
root: JsonSchema,
refPath: Set<string>,
budget: Budget,
): unknown {
if (schema == null || typeof schema !== "object" || budget.remaining <= 0) {
return null;
}
budget.remaining -= 1;
if (typeof schema.$ref === "string") {
if (refPath.has(schema.$ref)) {
return {};
}
const resolved = resolveRef(schema.$ref, root);
if (resolved == null) {
return {};
}
return buildValue(resolved, root, new Set(refPath).add(schema.$ref), budget);
}
if (Array.isArray(schema.enum)) {
return schema.enum[0] ?? "";
}
switch (schema.type) {
case "object":
return buildObject(schema, root, refPath, budget);
case "array":
return schema.items == null ? [] : [buildValue(schema.items, root, refPath, budget)];
case "string":
return buildString(schema.format);
case "number":
return 0;
case "boolean":
return false;
default:
return null;
}
}
function buildObject(
schema: JsonSchema,
root: JsonSchema,
refPath: Set<string>,
budget: Budget,
): unknown {
if (schema.properties != null && typeof schema.properties === "object") {
const example: Record<string, unknown> = {};
for (const [name, propertySchema] of Object.entries(schema.properties)) {
example[name] = buildValue(propertySchema, root, refPath, budget);
}
return example;
}
// Maps have no properties, only a value schema
if (schema.additionalProperties != null) {
return { key: buildValue(schema.additionalProperties, root, refPath, budget) };
}
return {};
}
function buildString(format: string | undefined): string {
if (format === "date-time") {
return new Date().toISOString();
}
// Duration JSON is a decimal string with an `s` suffix, and an empty one fails to parse
if (format === "duration") {
return "0s";
}
if (format != null && STRING_NUMBER_FORMATS.includes(format)) {
return "0";
}
return "";
}
function resolveRef(ref: string, root: JsonSchema): JsonSchema | null {
if (ref === ROOT_REF) {
return root;
}
if (!ref.startsWith(DEFS_PREFIX)) {
return null;
}
return root.$defs?.[ref.slice(DEFS_PREFIX.length)] ?? null;
}
+1 -6
View File
@@ -25,13 +25,8 @@ export async function showPromptForm({
id, id,
title, title,
description, description,
hideX: true,
size: size ?? "sm", size: size ?? "sm",
disableBackdropClose: true, // Prevent accidental dismisses disableClose: true,
onClose: () => {
// Click backdrop, close, or escape
resolve(null);
},
render: ({ hide }) => render: ({ hide }) =>
Prompt({ Prompt({
onCancel: () => { onCancel: () => {
+7 -14
View File
@@ -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
@@ -22,6 +22,7 @@ fn list(ctx: &CliContext, workspace_id: Option<&str>) -> CommandResult {
let workspace_id = resolve_workspace_id(ctx, workspace_id, "cookie-jar list")?; let workspace_id = resolve_workspace_id(ctx, workspace_id, "cookie-jar list")?;
let cookie_jars = ctx let cookie_jars = ctx
.db() .db()
.map_err(|e| e.to_string())?
.list_cookie_jars(&workspace_id) .list_cookie_jars(&workspace_id)
.map_err(|e| format!("Failed to list cookie jars: {e}"))?; .map_err(|e| format!("Failed to list cookie jars: {e}"))?;
@@ -50,6 +50,7 @@ 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() .db()
.map_err(|e| e.to_string())?
.list_environments_ensure_base(&workspace_id) .list_environments_ensure_base(&workspace_id)
.map_err(|e| format!("Failed to list environments: {e}"))?; .map_err(|e| format!("Failed to list environments: {e}"))?;
@@ -66,6 +67,7 @@ fn list(ctx: &CliContext, workspace_id: Option<&str>) -> CommandResult {
fn show(ctx: &CliContext, environment_id: &str) -> CommandResult { fn show(ctx: &CliContext, environment_id: &str) -> CommandResult {
let environment = ctx let environment = ctx
.db() .db()
.map_err(|e| e.to_string())?
.get_environment(environment_id) .get_environment(environment_id)
.map_err(|e| format!("Failed to get environment: {e}"))?; .map_err(|e| format!("Failed to get environment: {e}"))?;
let output = serde_json::to_string_pretty(&environment) let output = serde_json::to_string_pretty(&environment)
@@ -112,6 +114,7 @@ fn create(
let created = ctx let created = ctx
.db() .db()
.map_err(|e| e.to_string())?
.upsert_environment(&environment, &UpdateSource::Sync) .upsert_environment(&environment, &UpdateSource::Sync)
.map_err(|e| format!("Failed to create environment: {e}"))?; .map_err(|e| format!("Failed to create environment: {e}"))?;
@@ -134,6 +137,7 @@ fn create(
let created = ctx let created = ctx
.db() .db()
.map_err(|e| e.to_string())?
.upsert_environment(&environment, &UpdateSource::Sync) .upsert_environment(&environment, &UpdateSource::Sync)
.map_err(|e| format!("Failed to create environment: {e}"))?; .map_err(|e| format!("Failed to create environment: {e}"))?;
@@ -147,12 +151,14 @@ fn update(ctx: &CliContext, json: Option<String>, json_input: Option<String>) ->
let existing = ctx let existing = ctx
.db() .db()
.map_err(|e| e.to_string())?
.get_environment(&id) .get_environment(&id)
.map_err(|e| format!("Failed to get environment for update: {e}"))?; .map_err(|e| format!("Failed to get environment for update: {e}"))?;
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() .db()
.map_err(|e| e.to_string())?
.upsert_environment(&updated, &UpdateSource::Sync) .upsert_environment(&updated, &UpdateSource::Sync)
.map_err(|e| format!("Failed to update environment: {e}"))?; .map_err(|e| format!("Failed to update environment: {e}"))?;
@@ -168,6 +174,7 @@ fn delete(ctx: &CliContext, environment_id: &str, yes: bool) -> CommandResult {
let deleted = ctx let deleted = ctx
.db() .db()
.map_err(|e| e.to_string())?
.delete_environment_by_id(environment_id, &UpdateSource::Sync) .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}"))?;
+19 -6
View File
@@ -48,8 +48,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, "folder list")?; let workspace_id = resolve_workspace_id(ctx, workspace_id, "folder list")?;
let folders = let folders = ctx
ctx.db().list_folders(&workspace_id).map_err(|e| format!("Failed to list folders: {e}"))?; .db()
.map_err(|e| e.to_string())?
.list_folders(&workspace_id)
.map_err(|e| format!("Failed to list folders: {e}"))?;
if folders.is_empty() { if folders.is_empty() {
println!("No folders found in workspace {}", workspace_id); println!("No folders found in workspace {}", workspace_id);
} else { } else {
@@ -61,8 +64,11 @@ fn list(ctx: &CliContext, workspace_id: Option<&str>) -> CommandResult {
} }
fn show(ctx: &CliContext, folder_id: &str) -> CommandResult { fn show(ctx: &CliContext, folder_id: &str) -> CommandResult {
let folder = let folder = ctx
ctx.db().get_folder(folder_id).map_err(|e| format!("Failed to get folder: {e}"))?; .db()
.map_err(|e| e.to_string())?
.get_folder(folder_id)
.map_err(|e| format!("Failed to get folder: {e}"))?;
let output = serde_json::to_string_pretty(&folder) let output = serde_json::to_string_pretty(&folder)
.map_err(|e| format!("Failed to serialize folder: {e}"))?; .map_err(|e| format!("Failed to serialize folder: {e}"))?;
println!("{output}"); println!("{output}");
@@ -103,6 +109,7 @@ fn create(
let created = ctx let created = ctx
.db() .db()
.map_err(|e| e.to_string())?
.upsert_folder(&folder, &UpdateSource::Sync) .upsert_folder(&folder, &UpdateSource::Sync)
.map_err(|e| format!("Failed to create folder: {e}"))?; .map_err(|e| format!("Failed to create folder: {e}"))?;
@@ -119,6 +126,7 @@ fn create(
let created = ctx let created = ctx
.db() .db()
.map_err(|e| e.to_string())?
.upsert_folder(&folder, &UpdateSource::Sync) .upsert_folder(&folder, &UpdateSource::Sync)
.map_err(|e| format!("Failed to create folder: {e}"))?; .map_err(|e| format!("Failed to create folder: {e}"))?;
@@ -130,12 +138,16 @@ fn update(ctx: &CliContext, json: Option<String>, json_input: Option<String>) ->
let patch = parse_required_json(json, json_input, "folder update")?; let patch = parse_required_json(json, json_input, "folder update")?;
let id = require_id(&patch, "folder update")?; let id = require_id(&patch, "folder update")?;
let existing = let existing = ctx
ctx.db().get_folder(&id).map_err(|e| format!("Failed to get folder for update: {e}"))?; .db()
.map_err(|e| e.to_string())?
.get_folder(&id)
.map_err(|e| format!("Failed to get folder for update: {e}"))?;
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() .db()
.map_err(|e| e.to_string())?
.upsert_folder(&updated, &UpdateSource::Sync) .upsert_folder(&updated, &UpdateSource::Sync)
.map_err(|e| format!("Failed to update folder: {e}"))?; .map_err(|e| format!("Failed to update folder: {e}"))?;
@@ -151,6 +163,7 @@ fn delete(ctx: &CliContext, folder_id: &str, yes: bool) -> CommandResult {
let deleted = ctx let deleted = ctx
.db() .db()
.map_err(|e| e.to_string())?
.delete_folder_by_id(folder_id, &UpdateSource::Sync) .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}"))?;
@@ -5,16 +5,20 @@ use std::fs;
use std::io::ErrorKind; use std::io::ErrorKind;
use yaak::export::{self, ExportDataParams}; use yaak::export::{self, ExportDataParams};
use yaak::import; use yaak::import;
use yaak_core::WorkspaceContext; use yaak_models::util::{
use yaak_models::util::BatchUpsertResult; BatchUpsertResult, ImportDestination, ImportOrigin, ImportPlanAction, ImportPlanItem,
};
use yaak_plugins::events::{ImportResources, PluginContext}; use yaak_plugins::events::{ImportResources, PluginContext};
type CommandResult<T = ()> = std::result::Result<T, String>; type CommandResult<T = ()> = std::result::Result<T, String>;
pub async fn run_import(ctx: &CliContext, args: ImportArgs) -> i32 { pub async fn run_import(ctx: &CliContext, args: ImportArgs) -> i32 {
match import(ctx, args).await { match import(ctx, args).await {
Ok(result) => { Ok((result, items)) => {
println!("Imported {}", format_counts(&result)); println!("Imported {}", format_counts(&result));
if let Some(skipped) = format_skipped(&items) {
println!("Skipped {skipped}");
}
0 0
} }
Err(error) => { Err(error) => {
@@ -37,9 +41,13 @@ pub fn run_export(ctx: &CliContext, args: ExportArgs) -> i32 {
} }
} }
async fn import(ctx: &CliContext, args: ImportArgs) -> CommandResult<BatchUpsertResult> { async fn import(
ctx: &CliContext,
args: ImportArgs,
) -> CommandResult<(BatchUpsertResult, Vec<ImportPlanItem>)> {
if let Some(workspace_id) = args.workspace_id.as_deref() { if let Some(workspace_id) = args.workspace_id.as_deref() {
ctx.db() ctx.db()
.map_err(|e| e.to_string())?
.get_workspace(workspace_id) .get_workspace(workspace_id)
.map_err(|e| format!("Failed to get workspace '{workspace_id}': {e}"))?; .map_err(|e| format!("Failed to get workspace '{workspace_id}': {e}"))?;
} }
@@ -51,6 +59,7 @@ async fn import(ctx: &CliContext, args: ImportArgs) -> CommandResult<BatchUpsert
.import_data(&plugin_context, &file_contents) .import_data(&plugin_context, &file_contents)
.await .await
.map_err(|e| format!("Failed to import data: {e}"))?; .map_err(|e| format!("Failed to import data: {e}"))?;
let importer = import_result.importer;
let resources = import_result.resources; let resources = import_result.resources;
let workspace_id = args.workspace_id; let workspace_id = args.workspace_id;
if workspace_id.is_none() && resources_need_current_workspace(&resources) { if workspace_id.is_none() && resources_need_current_workspace(&resources) {
@@ -59,15 +68,62 @@ async fn import(ctx: &CliContext, args: ImportArgs) -> CommandResult<BatchUpsert
.to_string(), .to_string(),
); );
} }
let workspace_context = WorkspaceContext { let destination = match workspace_id {
workspace_id, Some(workspace_id) => ImportDestination::ExistingWorkspace { workspace_id, folder_id: None },
environment_id: None, None => ImportDestination::NewWorkspace,
cookie_jar_id: None,
request_id: None,
}; };
let imported = import::import_resources(ctx.query_manager(), workspace_context, resources) let plan = import::plan_import_resources(
ctx.query_manager(),
importer,
destination,
resources,
import_result.source_keys,
Some(file_origin(&args.file)),
)
.map_err(|e| format!("Failed to plan import: {e}"))?;
let items = plan.items.clone();
let imported = import::commit_import_plan(ctx.query_manager(), plan)
.map_err(|e| format!("Failed to import data: {e}"))?; .map_err(|e| format!("Failed to import data: {e}"))?;
Ok(imported) Ok((imported, items))
}
fn file_origin(path: &std::path::Path) -> ImportOrigin {
let canonical = fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
let label = canonical
.file_name()
.map(|name| name.to_string_lossy().to_string())
.unwrap_or_else(|| path.display().to_string());
ImportOrigin { origin: canonical.to_string_lossy().to_string(), label }
}
/// Summarize what the default selection left untouched during a merging re-import.
fn format_skipped(items: &[ImportPlanItem]) -> Option<String> {
let count = |action: ImportPlanAction| items.iter().filter(|i| i.action == action).count();
let plural = |n: usize| if n == 1 { "" } else { "s" };
let mut parts = Vec::new();
let deletions = count(ImportPlanAction::Delete);
if deletions > 0 {
parts.push(format!("{deletions} removed from source (not deleted locally)"));
}
let conflicts = count(ImportPlanAction::Conflict);
if conflicts > 0 {
parts.push(format!("{conflicts} conflict{} (kept local changes)", plural(conflicts)));
}
let keep_local = count(ImportPlanAction::KeepLocal);
if keep_local > 0 {
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);
if unchanged > 0 {
parts.push(format!("{unchanged} unchanged"));
}
if parts.is_empty() { None } else { Some(parts.join(", ")) }
} }
fn export(ctx: &CliContext, args: ExportArgs) -> CommandResult<usize> { fn export(ctx: &CliContext, args: ExportArgs) -> CommandResult<usize> {
@@ -91,8 +147,11 @@ fn resolve_export_workspace_ids(
all: bool, all: bool,
) -> CommandResult<Vec<String>> { ) -> CommandResult<Vec<String>> {
if all { if all {
let workspaces = let workspaces = ctx
ctx.db().list_workspaces().map_err(|e| format!("Failed to list workspaces: {e}"))?; .db()
.map_err(|e| e.to_string())?
.list_workspaces()
.map_err(|e| format!("Failed to list workspaces: {e}"))?;
if workspaces.is_empty() { if workspaces.is_empty() {
return Err("No workspaces found to export".to_string()); return Err("No workspaces found to export".to_string());
} }
@@ -105,6 +164,7 @@ fn resolve_export_workspace_ids(
for workspace_id in &workspace_ids { for workspace_id in &workspace_ids {
ctx.db() ctx.db()
.map_err(|e| e.to_string())?
.get_workspace(workspace_id) .get_workspace(workspace_id)
.map_err(|e| format!("Failed to get workspace '{workspace_id}': {e}"))?; .map_err(|e| format!("Failed to get workspace '{workspace_id}': {e}"))?;
} }
@@ -349,6 +349,7 @@ async fn install_from_directory(context: &CliContext, source: &str) -> CommandRe
let plugin = context let plugin = context
.db() .db()
.map_err(|e| e.to_string())?
.upsert_plugin( .upsert_plugin(
&Plugin { &Plugin {
directory: plugin_dir_str, directory: plugin_dir_str,
+17 -4
View File
@@ -71,6 +71,7 @@ fn list(ctx: &CliContext, workspace_id: Option<&str>) -> CommandResult {
let workspace_id = resolve_workspace_id(ctx, workspace_id, "request list")?; let workspace_id = resolve_workspace_id(ctx, workspace_id, "request list")?;
let requests = ctx let requests = ctx
.db() .db()
.map_err(|e| e.to_string())?
.list_http_requests(&workspace_id) .list_http_requests(&workspace_id)
.map_err(|e| format!("Failed to list requests: {e}"))?; .map_err(|e| format!("Failed to list requests: {e}"))?;
if requests.is_empty() { if requests.is_empty() {
@@ -425,6 +426,7 @@ fn create(
let created = ctx let created = ctx
.db() .db()
.map_err(|e| e.to_string())?
.upsert_http_request(&request, &UpdateSource::Sync) .upsert_http_request(&request, &UpdateSource::Sync)
.map_err(|e| format!("Failed to create request: {e}"))?; .map_err(|e| format!("Failed to create request: {e}"))?;
@@ -444,6 +446,7 @@ fn create(
let created = ctx let created = ctx
.db() .db()
.map_err(|e| e.to_string())?
.upsert_http_request(&request, &UpdateSource::Sync) .upsert_http_request(&request, &UpdateSource::Sync)
.map_err(|e| format!("Failed to create request: {e}"))?; .map_err(|e| format!("Failed to create request: {e}"))?;
@@ -458,12 +461,14 @@ fn update(ctx: &CliContext, json: Option<String>, json_input: Option<String>) ->
let existing = ctx let existing = ctx
.db() .db()
.map_err(|e| e.to_string())?
.get_http_request(&id) .get_http_request(&id)
.map_err(|e| format!("Failed to get request for update: {e}"))?; .map_err(|e| format!("Failed to get request for update: {e}"))?;
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() .db()
.map_err(|e| e.to_string())?
.upsert_http_request(&updated, &UpdateSource::Sync) .upsert_http_request(&updated, &UpdateSource::Sync)
.map_err(|e| format!("Failed to update request: {e}"))?; .map_err(|e| format!("Failed to update request: {e}"))?;
@@ -472,8 +477,11 @@ fn update(ctx: &CliContext, json: Option<String>, json_input: Option<String>) ->
} }
fn show(ctx: &CliContext, request_id: &str) -> CommandResult { fn show(ctx: &CliContext, request_id: &str) -> CommandResult {
let request = let request = ctx
ctx.db().get_http_request(request_id).map_err(|e| format!("Failed to get request: {e}"))?; .db()
.map_err(|e| e.to_string())?
.get_http_request(request_id)
.map_err(|e| format!("Failed to get request: {e}"))?;
let output = serde_json::to_string_pretty(&request) let output = serde_json::to_string_pretty(&request)
.map_err(|e| format!("Failed to serialize request: {e}"))?; .map_err(|e| format!("Failed to serialize request: {e}"))?;
println!("{output}"); println!("{output}");
@@ -488,6 +496,7 @@ fn delete(ctx: &CliContext, request_id: &str, yes: bool) -> CommandResult {
let deleted = ctx let deleted = ctx
.db() .db()
.map_err(|e| e.to_string())?
.delete_http_request_by_id(request_id, &UpdateSource::Sync) .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);
@@ -502,8 +511,11 @@ pub async fn send_request_by_id(
cookie_jar_id: Option<&str>, cookie_jar_id: Option<&str>,
verbose: bool, verbose: bool,
) -> Result<(), String> { ) -> Result<(), String> {
let request = let request = ctx
ctx.db().get_any_request(request_id).map_err(|e| format!("Failed to get request: {e}"))?; .db()
.map_err(|e| e.to_string())?
.get_any_request(request_id)
.map_err(|e| format!("Failed to get request: {e}"))?;
match request { match request {
AnyRequest::HttpRequest(http_request) => { AnyRequest::HttpRequest(http_request) => {
send_http_request_by_id( send_http_request_by_id(
@@ -611,6 +623,7 @@ pub(crate) fn resolve_cookie_jar_id(
let default_cookie_jar = ctx let default_cookie_jar = ctx
.db() .db()
.map_err(|e| e.to_string())?
.list_cookie_jars(workspace_id) .list_cookie_jars(workspace_id)
.map_err(|e| format!("Failed to list cookie jars: {e}"))? .map_err(|e| format!("Failed to list cookie jars: {e}"))?
.into_iter() .into_iter()
+9 -4
View File
@@ -27,13 +27,14 @@ pub fn run(ctx: &CliContext, args: ResponseArgs) -> i32 {
/// Accepts a response ID, or a request ID meaning "the latest response for that request". /// Accepts a response ID, or a request ID meaning "the latest response for that request".
fn resolve_response(ctx: &CliContext, id: &str) -> CommandResult<HttpResponse> { fn resolve_response(ctx: &CliContext, id: &str) -> CommandResult<HttpResponse> {
if let Ok(response) = ctx.db().get_http_response(id) { if let Ok(response) = ctx.db().map_err(|e| e.to_string())?.get_http_response(id) {
return Ok(response); return Ok(response);
} }
if ctx.db().get_http_request(id).is_ok() { if ctx.db().map_err(|e| e.to_string())?.get_http_request(id).is_ok() {
return ctx return ctx
.db() .db()
.map_err(|e| e.to_string())?
.list_http_responses_for_request(id, Some(1)) .list_http_responses_for_request(id, Some(1))
.map_err(|e| format!("Failed to list responses: {e}"))? .map_err(|e| format!("Failed to list responses: {e}"))?
.into_iter() .into_iter()
@@ -47,13 +48,15 @@ fn resolve_response(ctx: &CliContext, id: &str) -> CommandResult<HttpResponse> {
fn list(ctx: &CliContext, id: Option<&str>, limit: Option<u64>) -> CommandResult { fn list(ctx: &CliContext, id: Option<&str>, limit: Option<u64>) -> CommandResult {
// An explicit request ID scopes to that request; anything else lists the workspace. // An explicit request ID scopes to that request; anything else lists the workspace.
let responses = match id { let responses = match id {
Some(id) if ctx.db().get_http_request(id).is_ok() => ctx Some(id) if ctx.db().map_err(|e| e.to_string())?.get_http_request(id).is_ok() => ctx
.db() .db()
.map_err(|e| e.to_string())?
.list_http_responses_for_request(id, limit) .list_http_responses_for_request(id, limit)
.map_err(|e| format!("Failed to list responses: {e}"))?, .map_err(|e| format!("Failed to list responses: {e}"))?,
other => { other => {
let workspace_id = resolve_workspace_id(ctx, other, "response list")?; let workspace_id = resolve_workspace_id(ctx, other, "response list")?;
ctx.db() ctx.db()
.map_err(|e| e.to_string())?
.list_http_responses(&workspace_id, limit) .list_http_responses(&workspace_id, limit)
.map_err(|e| format!("Failed to list responses: {e}"))? .map_err(|e| format!("Failed to list responses: {e}"))?
} }
@@ -112,13 +115,14 @@ fn body(ctx: &CliContext, id: &str) -> CommandResult {
fn delete(ctx: &CliContext, id: &str, yes: bool) -> CommandResult { fn delete(ctx: &CliContext, id: &str, yes: bool) -> CommandResult {
// Deleting is scoped to a whole request or workspace, since a single stored // Deleting is scoped to a whole request or workspace, since a single stored
// response is rarely the thing someone wants to remove. // response is rarely the thing someone wants to remove.
if ctx.db().get_http_request(id).is_ok() { if ctx.db().map_err(|e| e.to_string())?.get_http_request(id).is_ok() {
if !yes && !confirm_delete("responses for request", id) { if !yes && !confirm_delete("responses for request", id) {
println!("Aborted"); println!("Aborted");
return Ok(()); return Ok(());
} }
let count = ctx let count = ctx
.db() .db()
.map_err(|e| e.to_string())?
.delete_all_http_responses_for_request(id, &UpdateSource::Sync) .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}");
@@ -132,6 +136,7 @@ fn delete(ctx: &CliContext, id: &str, yes: bool) -> CommandResult {
} }
let count = ctx let count = ctx
.db() .db()
.map_err(|e| e.to_string())?
.delete_all_http_responses_for_workspace(&workspace_id, &UpdateSource::Sync) .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}");
+9 -3
View File
@@ -34,7 +34,7 @@ async fn send_target(
) -> Result<(), String> { ) -> Result<(), String> {
let mode = if args.parallel { ExecutionMode::Parallel } else { ExecutionMode::Sequential }; let mode = if args.parallel { ExecutionMode::Parallel } else { ExecutionMode::Sequential };
if let Ok(request) = ctx.db().get_any_request(&args.id) { if let Ok(request) = ctx.db().map_err(|e| e.to_string())?.get_any_request(&args.id) {
let workspace_id = match &request { let workspace_id = match &request {
AnyRequest::HttpRequest(r) => r.workspace_id.clone(), AnyRequest::HttpRequest(r) => r.workspace_id.clone(),
AnyRequest::GrpcRequest(r) => r.workspace_id.clone(), AnyRequest::GrpcRequest(r) => r.workspace_id.clone(),
@@ -53,7 +53,7 @@ async fn send_target(
.await; .await;
} }
if let Ok(folder) = ctx.db().get_folder(&args.id) { if let Ok(folder) = ctx.db().map_err(|e| e.to_string())?.get_folder(&args.id) {
let resolved_cookie_jar_id = let resolved_cookie_jar_id =
request::resolve_cookie_jar_id(ctx, &folder.workspace_id, cookie_jar_id)?; request::resolve_cookie_jar_id(ctx, &folder.workspace_id, cookie_jar_id)?;
@@ -74,7 +74,7 @@ async fn send_target(
.await; .await;
} }
if let Ok(workspace) = ctx.db().get_workspace(&args.id) { if let Ok(workspace) = ctx.db().map_err(|e| e.to_string())?.get_workspace(&args.id) {
let resolved_cookie_jar_id = let resolved_cookie_jar_id =
request::resolve_cookie_jar_id(ctx, &workspace.id, cookie_jar_id)?; request::resolve_cookie_jar_id(ctx, &workspace.id, cookie_jar_id)?;
@@ -103,6 +103,7 @@ fn collect_folder_request_ids(ctx: &CliContext, folder_id: &str) -> Result<Vec<S
let mut http_ids = ctx let mut http_ids = ctx
.db() .db()
.map_err(|e| e.to_string())?
.list_http_requests_for_folder_recursive(folder_id) .list_http_requests_for_folder_recursive(folder_id)
.map_err(|e| format!("Failed to list HTTP requests in folder: {e}"))? .map_err(|e| format!("Failed to list HTTP requests in folder: {e}"))?
.into_iter() .into_iter()
@@ -112,6 +113,7 @@ fn collect_folder_request_ids(ctx: &CliContext, folder_id: &str) -> Result<Vec<S
let mut grpc_ids = ctx let mut grpc_ids = ctx
.db() .db()
.map_err(|e| e.to_string())?
.list_grpc_requests_for_folder_recursive(folder_id) .list_grpc_requests_for_folder_recursive(folder_id)
.map_err(|e| format!("Failed to list gRPC requests in folder: {e}"))? .map_err(|e| format!("Failed to list gRPC requests in folder: {e}"))?
.into_iter() .into_iter()
@@ -121,6 +123,7 @@ fn collect_folder_request_ids(ctx: &CliContext, folder_id: &str) -> Result<Vec<S
let mut websocket_ids = ctx let mut websocket_ids = ctx
.db() .db()
.map_err(|e| e.to_string())?
.list_websocket_requests_for_folder_recursive(folder_id) .list_websocket_requests_for_folder_recursive(folder_id)
.map_err(|e| format!("Failed to list WebSocket requests in folder: {e}"))? .map_err(|e| format!("Failed to list WebSocket requests in folder: {e}"))?
.into_iter() .into_iter()
@@ -139,6 +142,7 @@ fn collect_workspace_request_ids(
let mut http_ids = ctx let mut http_ids = ctx
.db() .db()
.map_err(|e| e.to_string())?
.list_http_requests(workspace_id) .list_http_requests(workspace_id)
.map_err(|e| format!("Failed to list HTTP requests in workspace: {e}"))? .map_err(|e| format!("Failed to list HTTP requests in workspace: {e}"))?
.into_iter() .into_iter()
@@ -148,6 +152,7 @@ fn collect_workspace_request_ids(
let mut grpc_ids = ctx let mut grpc_ids = ctx
.db() .db()
.map_err(|e| e.to_string())?
.list_grpc_requests(workspace_id) .list_grpc_requests(workspace_id)
.map_err(|e| format!("Failed to list gRPC requests in workspace: {e}"))? .map_err(|e| format!("Failed to list gRPC requests in workspace: {e}"))?
.into_iter() .into_iter()
@@ -157,6 +162,7 @@ fn collect_workspace_request_ids(
let mut websocket_ids = ctx let mut websocket_ids = ctx
.db() .db()
.map_err(|e| e.to_string())?
.list_websocket_requests(workspace_id) .list_websocket_requests(workspace_id)
.map_err(|e| format!("Failed to list WebSocket requests in workspace: {e}"))? .map_err(|e| format!("Failed to list WebSocket requests in workspace: {e}"))?
.into_iter() .into_iter()
+11 -2
View File
@@ -43,8 +43,11 @@ fn schema(pretty: bool) -> CommandResult {
} }
fn list(ctx: &CliContext) -> CommandResult { fn list(ctx: &CliContext) -> CommandResult {
let workspaces = let workspaces = ctx
ctx.db().list_workspaces().map_err(|e| format!("Failed to list workspaces: {e}"))?; .db()
.map_err(|e| e.to_string())?
.list_workspaces()
.map_err(|e| format!("Failed to list workspaces: {e}"))?;
if workspaces.is_empty() { if workspaces.is_empty() {
println!("No workspaces found"); println!("No workspaces found");
} else { } else {
@@ -58,6 +61,7 @@ fn list(ctx: &CliContext) -> CommandResult {
fn show(ctx: &CliContext, workspace_id: &str) -> CommandResult { fn show(ctx: &CliContext, workspace_id: &str) -> CommandResult {
let workspace = ctx let workspace = ctx
.db() .db()
.map_err(|e| e.to_string())?
.get_workspace(workspace_id) .get_workspace(workspace_id)
.map_err(|e| format!("Failed to get workspace: {e}"))?; .map_err(|e| format!("Failed to get workspace: {e}"))?;
let output = serde_json::to_string_pretty(&workspace) let output = serde_json::to_string_pretty(&workspace)
@@ -85,6 +89,7 @@ fn create(
let created = ctx let created = ctx
.db() .db()
.map_err(|e| e.to_string())?
.upsert_workspace(&workspace, &UpdateSource::Sync) .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);
@@ -98,6 +103,7 @@ fn create(
let workspace = Workspace { name, ..Default::default() }; let workspace = Workspace { name, ..Default::default() };
let created = ctx let created = ctx
.db() .db()
.map_err(|e| e.to_string())?
.upsert_workspace(&workspace, &UpdateSource::Sync) .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);
@@ -110,12 +116,14 @@ fn update(ctx: &CliContext, json: Option<String>, json_input: Option<String>) ->
let existing = ctx let existing = ctx
.db() .db()
.map_err(|e| e.to_string())?
.get_workspace(&id) .get_workspace(&id)
.map_err(|e| format!("Failed to get workspace for update: {e}"))?; .map_err(|e| format!("Failed to get workspace for update: {e}"))?;
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() .db()
.map_err(|e| e.to_string())?
.upsert_workspace(&updated, &UpdateSource::Sync) .upsert_workspace(&updated, &UpdateSource::Sync)
.map_err(|e| format!("Failed to update workspace: {e}"))?; .map_err(|e| format!("Failed to update workspace: {e}"))?;
@@ -131,6 +139,7 @@ fn delete(ctx: &CliContext, workspace_id: &str, yes: bool) -> CommandResult {
let deleted = ctx let deleted = ctx
.db() .db()
.map_err(|e| e.to_string())?
.delete_workspace_by_id(workspace_id, &UpdateSource::Sync, ctx.blob_manager()) .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);
+4 -6
View File
@@ -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( if let Ok(db) = query_manager.connect() {
&yaak_lifecycle::Host::guest(), let _ = yaak_lifecycle::on_launch(&yaak_lifecycle::Host::guest(), &db, &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));
@@ -120,7 +118,7 @@ impl CliContext {
&self.data_dir &self.data_dir
} }
pub fn db(&self) -> ClientDb<'_> { pub fn db(&self) -> yaak_models::error::Result<ClientDb<'_>> {
self.query_manager.connect() self.query_manager.connect()
} }
+5 -3
View File
@@ -203,7 +203,7 @@ fn resolve_send_execution_context(
environment: Option<&str>, environment: Option<&str>,
explicit_cookie_jar_id: Option<&str>, explicit_cookie_jar_id: Option<&str>,
) -> Result<CliExecutionContext, String> { ) -> Result<CliExecutionContext, String> {
if let Ok(request) = context.db().get_any_request(id) { if let Ok(request) = context.db().map_err(|e| e.to_string())?.get_any_request(id) {
let (request_id, workspace_id) = match request { let (request_id, workspace_id) = match request {
AnyRequest::HttpRequest(r) => (Some(r.id), r.workspace_id), AnyRequest::HttpRequest(r) => (Some(r.id), r.workspace_id),
AnyRequest::GrpcRequest(r) => (Some(r.id), r.workspace_id), AnyRequest::GrpcRequest(r) => (Some(r.id), r.workspace_id),
@@ -218,7 +218,7 @@ fn resolve_send_execution_context(
}); });
} }
if let Ok(folder) = context.db().get_folder(id) { if let Ok(folder) = context.db().map_err(|e| e.to_string())?.get_folder(id) {
let cookie_jar_id = let cookie_jar_id =
resolve_cookie_jar_id(context, &folder.workspace_id, explicit_cookie_jar_id)?; resolve_cookie_jar_id(context, &folder.workspace_id, explicit_cookie_jar_id)?;
return Ok(CliExecutionContext { return Ok(CliExecutionContext {
@@ -229,7 +229,7 @@ fn resolve_send_execution_context(
}); });
} }
if let Ok(workspace) = context.db().get_workspace(id) { if let Ok(workspace) = context.db().map_err(|e| e.to_string())?.get_workspace(id) {
let cookie_jar_id = resolve_cookie_jar_id(context, &workspace.id, explicit_cookie_jar_id)?; let cookie_jar_id = resolve_cookie_jar_id(context, &workspace.id, explicit_cookie_jar_id)?;
return Ok(CliExecutionContext { return Ok(CliExecutionContext {
request_id: None, request_id: None,
@@ -250,6 +250,7 @@ fn resolve_request_execution_context(
) -> Result<CliExecutionContext, String> { ) -> Result<CliExecutionContext, String> {
let request = context let request = context
.db() .db()
.map_err(|e| e.to_string())?
.get_any_request(request_id) .get_any_request(request_id)
.map_err(|e| format!("Failed to get request: {e}"))?; .map_err(|e| format!("Failed to get request: {e}"))?;
@@ -279,6 +280,7 @@ fn resolve_cookie_jar_id(
let default_cookie_jar = context let default_cookie_jar = context
.db() .db()
.map_err(|e| e.to_string())?
.list_cookie_jars(workspace_id) .list_cookie_jars(workspace_id)
.map_err(|e| format!("Failed to list cookie jars: {e}"))? .map_err(|e| format!("Failed to list cookie jars: {e}"))?
.into_iter() .into_iter()
+69 -52
View File
@@ -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,
@@ -150,7 +150,11 @@ async fn build_plugin_reply(
Some(InternalEventPayload::ShowToastResponse(EmptyPayload {})) Some(InternalEventPayload::ShowToastResponse(EmptyPayload {}))
} }
HostRequest::ListOpenWorkspaces(_) => { HostRequest::ListOpenWorkspaces(_) => {
let workspaces = match host_context.query_manager.connect().list_workspaces() { let workspaces = match host_context
.query_manager
.connect()
.and_then(|db| db.list_workspaces())
{
Ok(workspaces) => workspaces Ok(workspaces) => workspaces
.into_iter() .into_iter()
.map(|w| WorkspaceInfo { id: w.id.clone(), name: w.name, label: w.id }) .map(|w| WorkspaceInfo { id: w.id.clone(), name: w.name, label: w.id })
@@ -189,7 +193,7 @@ async fn build_plugin_reply(
match host_context match host_context
.query_manager .query_manager
.connect() .connect()
.list_cookie_jars(http_request.workspace_id.as_str()) .and_then(|db| db.list_cookie_jars(http_request.workspace_id.as_str()))
{ {
Ok(cookie_jars) => cookie_jars Ok(cookie_jars) => cookie_jars
.into_iter() .into_iter()
@@ -264,19 +268,20 @@ async fn build_plugin_reply(
..event.context.clone() ..event.context.clone()
}; };
let environment_chain = let environment_chain = match host_context.query_manager.connect().and_then(|db| {
match host_context.query_manager.connect().resolve_environments( db.resolve_environments(
&grpc_request.workspace_id, &grpc_request.workspace_id,
grpc_request.folder_id.as_deref(), grpc_request.folder_id.as_deref(),
execution_context.environment_id.as_deref(), execution_context.environment_id.as_deref(),
) { )
Ok(chain) => chain, }) {
Err(err) => { Ok(chain) => chain,
return Some(InternalEventPayload::ErrorResponse(ErrorResponse { Err(err) => {
error: format!("Failed to resolve environments in CLI: {err}"), return Some(InternalEventPayload::ErrorResponse(ErrorResponse {
})); error: format!("Failed to resolve environments in CLI: {err}"),
} }));
}; }
};
let template_callback = PluginTemplateCallback::new( let template_callback = PluginTemplateCallback::new(
host_context.plugin_manager.clone(), host_context.plugin_manager.clone(),
@@ -324,19 +329,20 @@ async fn build_plugin_reply(
..event.context.clone() ..event.context.clone()
}; };
let environment_chain = let environment_chain = match host_context.query_manager.connect().and_then(|db| {
match host_context.query_manager.connect().resolve_environments( db.resolve_environments(
&http_request.workspace_id, &http_request.workspace_id,
http_request.folder_id.as_deref(), http_request.folder_id.as_deref(),
execution_context.environment_id.as_deref(), execution_context.environment_id.as_deref(),
) { )
Ok(chain) => chain, }) {
Err(err) => { Ok(chain) => chain,
return Some(InternalEventPayload::ErrorResponse(ErrorResponse { Err(err) => {
error: format!("Failed to resolve environments in CLI: {err}"), return Some(InternalEventPayload::ErrorResponse(ErrorResponse {
})); error: format!("Failed to resolve environments in CLI: {err}"),
} }));
}; }
};
let template_callback = PluginTemplateCallback::new( let template_callback = PluginTemplateCallback::new(
host_context.plugin_manager.clone(), host_context.plugin_manager.clone(),
@@ -380,7 +386,11 @@ async fn build_plugin_reply(
}; };
let folder_id = execution_context.request_id.as_ref().and_then(|rid| { let folder_id = execution_context.request_id.as_ref().and_then(|rid| {
match host_context.query_manager.connect().get_any_request(rid) { match host_context
.query_manager
.connect()
.and_then(|db| db.get_any_request(rid))
{
Ok(AnyRequest::HttpRequest(r)) => r.folder_id, Ok(AnyRequest::HttpRequest(r)) => r.folder_id,
Ok(AnyRequest::GrpcRequest(r)) => r.folder_id, Ok(AnyRequest::GrpcRequest(r)) => r.folder_id,
Ok(AnyRequest::WebsocketRequest(r)) => r.folder_id, Ok(AnyRequest::WebsocketRequest(r)) => r.folder_id,
@@ -388,19 +398,20 @@ async fn build_plugin_reply(
} }
}); });
let environment_chain = let environment_chain = match host_context.query_manager.connect().and_then(|db| {
match host_context.query_manager.connect().resolve_environments( db.resolve_environments(
&workspace_id, &workspace_id,
folder_id.as_deref(), folder_id.as_deref(),
execution_context.environment_id.as_deref(), execution_context.environment_id.as_deref(),
) { )
Ok(chain) => chain, }) {
Err(err) => { Ok(chain) => chain,
return Some(InternalEventPayload::ErrorResponse(ErrorResponse { Err(err) => {
error: format!("Failed to resolve environments in CLI: {err}"), return Some(InternalEventPayload::ErrorResponse(ErrorResponse {
})); error: format!("Failed to resolve environments in CLI: {err}"),
} }));
}; }
};
let template_callback = PluginTemplateCallback::new( let template_callback = PluginTemplateCallback::new(
host_context.plugin_manager.clone(), host_context.plugin_manager.clone(),
@@ -476,15 +487,18 @@ async fn build_plugin_reply(
)); ));
}; };
let cookie_jar = let cookie_jar = match host_context
match host_context.query_manager.connect().get_cookie_jar(cookie_jar_id) { .query_manager
Ok(cookie_jar) => cookie_jar, .connect()
Err(err) => { .and_then(|db| db.get_cookie_jar(cookie_jar_id))
return Some(InternalEventPayload::ErrorResponse(ErrorResponse { {
error: format!("Failed to load cookie jar in CLI: {err}"), Ok(cookie_jar) => cookie_jar,
})); Err(err) => {
} return Some(InternalEventPayload::ErrorResponse(ErrorResponse {
}; error: format!("Failed to load cookie jar in CLI: {err}"),
}));
}
};
let names = cookie_jar.cookies.into_iter().map(|c| c.name).collect(); let names = cookie_jar.cookies.into_iter().map(|c| c.name).collect();
@@ -499,15 +513,18 @@ async fn build_plugin_reply(
)); ));
}; };
let cookie_jar = let cookie_jar = match host_context
match host_context.query_manager.connect().get_cookie_jar(cookie_jar_id) { .query_manager
Ok(cookie_jar) => cookie_jar, .connect()
Err(err) => { .and_then(|db| db.get_cookie_jar(cookie_jar_id))
return Some(InternalEventPayload::ErrorResponse(ErrorResponse { {
error: format!("Failed to load cookie jar in CLI: {err}"), Ok(cookie_jar) => cookie_jar,
})); Err(err) => {
} return Some(InternalEventPayload::ErrorResponse(ErrorResponse {
}; error: format!("Failed to load cookie jar in CLI: {err}"),
}));
}
};
let value = let value =
get_cookie_value_from_jar(cookie_jar.cookies, &req.name, req.domain.as_deref()); get_cookie_value_from_jar(cookie_jar.cookies, &req.name, req.domain.as_deref());
+5 -2
View File
@@ -9,8 +9,11 @@ pub fn resolve_workspace_id(
return Ok(workspace_id.to_string()); return Ok(workspace_id.to_string());
} }
let workspaces = let workspaces = ctx
ctx.db().list_workspaces().map_err(|e| format!("Failed to list workspaces: {e}"))?; .db()
.map_err(|e| e.to_string())?
.list_workspaces()
.map_err(|e| format!("Failed to list workspaces: {e}"))?;
match workspaces.as_slice() { match workspaces.as_slice() {
[] => Err(format!("No workspaces found. {command_name} requires a workspace ID.")), [] => Err(format!("No workspaces found. {command_name} requires a workspace ID.")),
[workspace] => Ok(workspace.id.clone()), [workspace] => Ok(workspace.id.clone()),
+5
View File
@@ -41,6 +41,7 @@ pub fn seed_workspace(data_dir: &Path, workspace_id: &str) {
query_manager(data_dir) query_manager(data_dir)
.connect() .connect()
.unwrap()
.upsert_workspace(&workspace, &UpdateSource::Sync) .upsert_workspace(&workspace, &UpdateSource::Sync)
.expect("Failed to seed workspace"); .expect("Failed to seed workspace");
} }
@@ -57,6 +58,7 @@ pub fn seed_request(data_dir: &Path, workspace_id: &str, request_id: &str) {
query_manager(data_dir) query_manager(data_dir)
.connect() .connect()
.unwrap()
.upsert_http_request(&request, &UpdateSource::Sync) .upsert_http_request(&request, &UpdateSource::Sync)
.expect("Failed to seed request"); .expect("Failed to seed request");
} }
@@ -71,6 +73,7 @@ pub fn seed_folder(data_dir: &Path, workspace_id: &str, folder_id: &str) {
query_manager(data_dir) query_manager(data_dir)
.connect() .connect()
.unwrap()
.upsert_folder(&folder, &UpdateSource::Sync) .upsert_folder(&folder, &UpdateSource::Sync)
.expect("Failed to seed folder"); .expect("Failed to seed folder");
} }
@@ -86,6 +89,7 @@ pub fn seed_grpc_request(data_dir: &Path, workspace_id: &str, request_id: &str)
query_manager(data_dir) query_manager(data_dir)
.connect() .connect()
.unwrap()
.upsert_grpc_request(&request, &UpdateSource::Sync) .upsert_grpc_request(&request, &UpdateSource::Sync)
.expect("Failed to seed gRPC request"); .expect("Failed to seed gRPC request");
} }
@@ -101,6 +105,7 @@ pub fn seed_websocket_request(data_dir: &Path, workspace_id: &str, request_id: &
query_manager(data_dir) query_manager(data_dir)
.connect() .connect()
.unwrap()
.upsert_websocket_request(&request, &UpdateSource::Sync) .upsert_websocket_request(&request, &UpdateSource::Sync)
.expect("Failed to seed WebSocket request"); .expect("Failed to seed WebSocket request");
} }
@@ -42,7 +42,7 @@ fn create_list_show_delete_round_trip() {
.success() .success()
.stdout(contains(format!("Deleted environment: {environment_id}"))); .stdout(contains(format!("Deleted environment: {environment_id}")));
assert!(query_manager(data_dir).connect().get_environment(&environment_id).is_err()); assert!(query_manager(data_dir).connect().unwrap().get_environment(&environment_id).is_err());
} }
#[test] #[test]
+1 -1
View File
@@ -36,7 +36,7 @@ fn create_list_show_delete_round_trip() {
.success() .success()
.stdout(contains(format!("Deleted folder: {folder_id}"))); .stdout(contains(format!("Deleted folder: {folder_id}")));
assert!(query_manager(data_dir).connect().get_folder(&folder_id).is_err()); assert!(query_manager(data_dir).connect().unwrap().get_folder(&folder_id).is_err());
} }
#[test] #[test]
@@ -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() {
@@ -80,15 +81,22 @@ fn import_reads_yaak_workspace_file() {
.stdout(contains("Imported 1 workspace, 1 HTTP request")); .stdout(contains("Imported 1 workspace, 1 HTTP request"));
let query_manager = query_manager(data_dir); let query_manager = query_manager(data_dir);
let db = query_manager.connect(); let db = query_manager.connect().unwrap();
assert_eq!( let workspaces = db.list_workspaces().expect("list imported workspaces");
db.get_workspace("wrk_import").expect("workspace imported").name, let workspace = workspaces
"Imported Workspace" .iter()
); .find(|workspace| workspace.name == "Imported Workspace")
assert_eq!( .expect("workspace imported");
db.get_http_request("req_import").expect("request imported").url, assert_ne!(workspace.id, "wrk_import");
"https://example.com"
); let requests = db.list_http_requests(&workspace.id).expect("list imported requests");
let request = requests
.iter()
.find(|request| request.name == "Imported Request")
.expect("request imported");
assert_ne!(request.id, "req_import");
assert_eq!(request.workspace_id, workspace.id);
assert_eq!(request.url, "https://example.com");
} }
fn write_postman_environment_fixture(path: &std::path::Path) { fn write_postman_environment_fixture(path: &std::path::Path) {
@@ -152,7 +160,7 @@ fn import_postman_environment_uses_workspace_id() {
.stdout(contains("Imported 1 environment")); .stdout(contains("Imported 1 environment"));
let query_manager = query_manager(data_dir); let query_manager = query_manager(data_dir);
let db = query_manager.connect(); let db = query_manager.connect().unwrap();
let environments = let environments =
db.list_environments_ensure_base(&workspace_id).expect("list imported environments"); db.list_environments_ensure_base(&workspace_id).expect("list imported environments");
@@ -160,3 +168,150 @@ fn import_postman_environment_uses_workspace_id() {
environments.iter().find(|e| e.name == "Local").expect("postman environment imported"); environments.iter().find(|e| e.name == "Local").expect("postman environment imported");
assert_eq!(imported_environment.workspace_id, workspace_id); assert_eq!(imported_environment.workspace_id, workspace_id);
} }
fn write_linked_fixture(path: &std::path::Path, requests: &[(&str, &str, &str)]) {
let requests = requests
.iter()
.map(|(id, name, url)| {
format!(
r#"{{ "model": "http_request", "id": "{id}", "workspaceId": "wrk_link",
"name": "{name}", "method": "GET", "url": "{url}" }}"#
)
})
.collect::<Vec<_>>()
.join(",");
std::fs::write(
path,
format!(
r#"{{
"yaakVersion": "test",
"yaakSchema": 4,
"resources": {{
"workspaces": [{{ "model": "workspace", "id": "wrk_link", "name": "Linked Workspace" }}],
"httpRequests": [{requests}]
}}
}}"#
),
)
.expect("write linked fixture");
}
#[test]
fn re_import_merges_into_linked_workspace() {
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()
.stdout(contains("Imported 1 workspace, 2 HTTP requests"));
let workspace_id = {
let query_manager = query_manager(data_dir);
let db = query_manager.connect().unwrap();
db.list_workspaces()
.expect("list workspaces")
.into_iter()
.find(|w| w.name == "Linked Workspace")
.expect("workspace imported")
.id
};
// The source doc changes A, drops B, and adds C. The default selection applies the
// update and the create but leaves the removal as an offer.
write_linked_fixture(
&import_path,
&[
("req_a", "Request A", "https://example.com/a-v2"),
("req_c", "Request C", "https://example.com/c"),
],
);
cli_cmd(data_dir)
.args([
"import",
import_path.to_str().expect("import path is utf-8"),
"--workspace-id",
&workspace_id,
])
.assert()
.success()
.stdout(contains("Imported 2 HTTP requests"))
.stdout(contains("Skipped 1 removed from source"));
let query_manager = query_manager(data_dir);
let db = query_manager.connect().unwrap();
let requests = db.list_http_requests(&workspace_id).expect("list requests");
assert_eq!(requests.len(), 3, "merge must not duplicate: {requests:?}");
assert_eq!(
requests.iter().find(|r| r.name == "Request A").expect("request A").url,
"https://example.com/a-v2"
);
assert!(requests.iter().any(|r| r.name == "Request B"), "removal must not auto-apply");
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().unwrap();
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");
db.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().unwrap().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");
}
@@ -43,7 +43,7 @@ fn show_and_delete_yes_round_trip() {
.success() .success()
.stdout(contains(format!("Deleted request: {request_id}"))); .stdout(contains(format!("Deleted request: {request_id}")));
assert!(query_manager(data_dir).connect().get_http_request(&request_id).is_err()); assert!(query_manager(data_dir).connect().unwrap().get_http_request(&request_id).is_err());
} }
#[test] #[test]
@@ -61,7 +61,11 @@ fn delete_without_yes_fails_in_non_interactive_mode() {
.stderr(contains("Refusing to delete in non-interactive mode without --yes")); .stderr(contains("Refusing to delete in non-interactive mode without --yes"));
assert!( assert!(
query_manager(data_dir).connect().get_http_request("rq_seed_delete_noninteractive").is_ok() query_manager(data_dir)
.connect()
.unwrap()
.get_http_request("rq_seed_delete_noninteractive")
.is_ok()
); );
} }
@@ -122,6 +126,7 @@ fn create_allows_workspace_only_with_empty_defaults() {
let request = query_manager(data_dir) let request = query_manager(data_dir)
.connect() .connect()
.unwrap()
.get_http_request(&request_id) .get_http_request(&request_id)
.expect("Failed to load created request"); .expect("Failed to load created request");
assert_eq!(request.workspace_id, "wk_test"); assert_eq!(request.workspace_id, "wk_test");
@@ -207,7 +212,7 @@ fn request_send_persists_response_body_and_events() {
.stdout(contains("hello from integration test")); .stdout(contains("hello from integration test"));
let qm = query_manager(data_dir); let qm = query_manager(data_dir);
let db = qm.connect(); let db = qm.connect().unwrap();
let responses = let responses =
db.list_http_responses_for_request(&request_id, None).expect("Failed to load responses"); db.list_http_responses_for_request(&request_id, None).expect("Failed to load responses");
assert_eq!(responses.len(), 1, "expected exactly one persisted response"); assert_eq!(responses.len(), 1, "expected exactly one persisted response");
@@ -26,6 +26,7 @@ fn top_level_send_folder_sends_http_requests_and_prints_summary() {
}; };
query_manager(data_dir) query_manager(data_dir)
.connect() .connect()
.unwrap()
.upsert_http_request(&request, &UpdateSource::Sync) .upsert_http_request(&request, &UpdateSource::Sync)
.expect("Failed to seed folder request"); .expect("Failed to seed folder request");
@@ -26,7 +26,7 @@ fn create_show_delete_round_trip() {
.success() .success()
.stdout(contains(format!("Deleted workspace: {workspace_id}"))); .stdout(contains(format!("Deleted workspace: {workspace_id}")));
assert!(query_manager(data_dir).connect().get_workspace(&workspace_id).is_err()); assert!(query_manager(data_dir).connect().unwrap().get_workspace(&workspace_id).is_err());
} }
#[test] #[test]
+2 -3
View File
@@ -3,11 +3,10 @@ use std::collections::BTreeMap;
use crate::PluginContextExt; use crate::PluginContextExt;
use crate::error::Result; use crate::error::Result;
use KeyAndValueRef::{Ascii, Binary}; use KeyAndValueRef::{Ascii, Binary};
use tauri::{Manager, Runtime, WebviewWindow}; use tauri::{Runtime, WebviewWindow};
use yaak_grpc::{KeyAndValueRef, MetadataMap}; use yaak_grpc::{KeyAndValueRef, MetadataMap};
use yaak_models::models::GrpcRequest; use yaak_models::models::GrpcRequest;
use yaak_plugins::events::{CallHttpAuthenticationRequest, HttpHeader}; use yaak_plugins::events::{CallHttpAuthenticationRequest, HttpHeader};
use yaak_plugins::manager::PluginManager;
pub(crate) fn metadata_to_map(metadata: MetadataMap) -> BTreeMap<String, String> { pub(crate) fn metadata_to_map(metadata: MetadataMap) -> BTreeMap<String, String> {
let mut entries = BTreeMap::new(); let mut entries = BTreeMap::new();
@@ -26,7 +25,7 @@ pub(crate) async fn build_metadata<R: Runtime>(
request: &GrpcRequest, request: &GrpcRequest,
authentication_context_id: &str, authentication_context_id: &str,
) -> Result<BTreeMap<String, String>> { ) -> Result<BTreeMap<String, String>> {
let plugin_manager = window.state::<PluginManager>(); let plugin_manager = crate::plugins_ext::plugin_manager(window).await?;
let mut metadata = BTreeMap::new(); let mut metadata = BTreeMap::new();
// Add the rest of metadata // Add the rest of metadata
+5 -4
View File
@@ -27,12 +27,9 @@ pub fn get_or_upsert_launch_info<R: Runtime>(app_handle: &AppHandle<R>) -> &Laun
LAUNCH_INFO.get_or_init(|| { LAUNCH_INFO.get_or_init(|| {
let now = Utc::now().naive_utc(); let now = Utc::now().naive_utc();
let mut info = LaunchEventInfo { let mut info = LaunchEventInfo {
version_since: app_handle.db().get_key_value_dte(NAMESPACE, VERSION_SINCE_KEY, now),
current_version: app_handle.package_info().version.to_string(), current_version: app_handle.package_info().version.to_string(),
user_since: app_handle.db().get_settings().created_at,
num_launches: app_handle.db().get_key_value_int(NAMESPACE, NUM_LAUNCHES_KEY, 0) + 1,
// The rest will be set below // The rest is read and written inside the transaction below
..Default::default() ..Default::default()
}; };
@@ -42,6 +39,10 @@ pub fn get_or_upsert_launch_info<R: Runtime>(app_handle: &AppHandle<R>) -> &Laun
app_handle app_handle
.with_tx(|tx| { .with_tx(|tx| {
info.version_since = tx.get_key_value_dte(NAMESPACE, VERSION_SINCE_KEY, now);
info.user_since = tx.get_settings().created_at;
info.num_launches = tx.get_key_value_int(NAMESPACE, NUM_LAUNCHES_KEY, 0) + 1;
// Load the previously tracked version // Load the previously tracked version
let curr_db = tx.get_key_value_str(NAMESPACE, LAST_VERSION_KEY, ""); let curr_db = tx.get_key_value_str(NAMESPACE, LAST_VERSION_KEY, "");
let prev_db = tx.get_key_value_str(NAMESPACE, PREV_VERSION_KEY, ""); let prev_db = tx.get_key_value_str(NAMESPACE, PREV_VERSION_KEY, "");
@@ -14,7 +14,6 @@ use yaak_http::manager::HttpConnectionManager;
use yaak_models::models::{CookieJar, Environment, HttpRequest, HttpResponse, HttpResponseState}; use yaak_models::models::{CookieJar, Environment, HttpRequest, HttpResponse, HttpResponseState};
use yaak_models::util::UpdateSource; use yaak_models::util::UpdateSource;
use yaak_plugins::events::PluginContext; use yaak_plugins::events::PluginContext;
use yaak_plugins::manager::PluginManager;
/// Context for managing response state during HTTP transactions. /// Context for managing response state during HTTP transactions.
/// Handles both persisted responses (stored in DB) and ephemeral responses (in-memory only). /// Handles both persisted responses (stored in DB) and ephemeral responses (in-memory only).
@@ -149,7 +148,7 @@ async fn send_http_request_inner<R: Runtime>(
response_ctx: &mut ResponseContext<R>, response_ctx: &mut ResponseContext<R>,
) -> Result<SentHttpRequest> { ) -> Result<SentHttpRequest> {
let app_handle = window.app_handle().clone(); let app_handle = window.app_handle().clone();
let plugin_manager = Arc::new((*app_handle.state::<PluginManager>()).clone()); let plugin_manager = Arc::new(crate::plugins_ext::plugin_manager(&app_handle).await?);
let encryption_manager = Arc::new((*app_handle.state::<EncryptionManager>()).clone()); let encryption_manager = Arc::new((*app_handle.state::<EncryptionManager>()).clone());
let connection_manager = app_handle.state::<HttpConnectionManager>(); let connection_manager = app_handle.state::<HttpConnectionManager>();
let environment_id = environment.map(|e| e.id); let environment_id = environment.map(|e| e.id);
+53 -22
View File
@@ -4,53 +4,84 @@ use crate::models_ext::QueryManagerExt;
use std::fs::read_to_string; use std::fs::read_to_string;
use std::io::ErrorKind; use std::io::ErrorKind;
use tauri::{Manager, Runtime, WebviewWindow}; use tauri::{Manager, Runtime, WebviewWindow};
use yaak::import::{self, ImportDataParams}; use yaak::import::{self, PlanImportDataParams};
use yaak_api::{ApiClientKind, yaak_api_client}; use yaak_api::{ApiClientKind, yaak_api_client};
use yaak_core::WorkspaceContext; use yaak_models::util::{BatchUpsertResult, ImportDestination, ImportOrigin, ImportPlan};
use yaak_models::util::BatchUpsertResult;
use yaak_plugins::manager::PluginManager;
use yaak_tauri_utils::window::WorkspaceWindowTrait;
pub(crate) async fn import_data<R: Runtime>( pub(crate) async fn import_data<R: Runtime>(
window: &WebviewWindow<R>, window: &WebviewWindow<R>,
file_path: &str, file_path: &str,
origin: Option<ImportOrigin>,
) -> Result<BatchUpsertResult> { ) -> Result<BatchUpsertResult> {
let contents = read_import_file(file_path)?; let contents = read_import_file(file_path)?;
import_contents(window, &contents).await let plan =
plan_import_contents(window, &contents, ImportDestination::NewWorkspace, origin).await?;
commit_import(window, plan)
} }
pub(crate) async fn import_url<R: Runtime>( pub(crate) async fn plan_import_data<R: Runtime>(
window: &WebviewWindow<R>,
file_path: &str,
destination: ImportDestination,
) -> Result<ImportPlan> {
let contents = read_import_file(file_path)?;
plan_import_contents(window, &contents, destination, Some(file_origin(file_path))).await
}
pub(crate) async fn plan_import_url<R: Runtime>(
window: &WebviewWindow<R>, window: &WebviewWindow<R>,
url: &str, url: &str,
) -> Result<BatchUpsertResult> { destination: ImportDestination,
let contents = fetch_import_url(window, url).await?; ) -> Result<ImportPlan> {
import_contents(window, &contents).await let url = normalize_import_url(url)?;
let contents = fetch_import_url(window, &url).await?;
plan_import_contents(window, &contents, destination, Some(url_origin(&url))).await
} }
async fn import_contents<R: Runtime>( async fn plan_import_contents<R: Runtime>(
window: &WebviewWindow<R>, window: &WebviewWindow<R>,
contents: &str, contents: &str,
) -> Result<BatchUpsertResult> { destination: ImportDestination,
let plugin_manager = window.state::<PluginManager>(); origin: Option<ImportOrigin>,
) -> Result<ImportPlan> {
let plugin_manager = crate::plugins_ext::plugin_manager(window).await?;
let query_manager = window.db_manager(); let query_manager = window.db_manager();
let plugin_context = window.plugin_context(); let plugin_context = window.plugin_context();
let workspace_context = WorkspaceContext {
workspace_id: window.workspace_id(),
environment_id: window.environment_id(),
cookie_jar_id: window.cookie_jar_id(),
request_id: None,
};
Ok(import::import_data(ImportDataParams { Ok(import::plan_import_data(PlanImportDataParams {
query_manager: &query_manager, query_manager: &query_manager,
plugin_manager: &plugin_manager, plugin_manager: &plugin_manager,
plugin_context: &plugin_context, plugin_context: &plugin_context,
workspace_context, destination,
contents, contents,
origin,
}) })
.await?) .await?)
} }
/// Canonicalize so re-importing the same file through a different spelling of its path still
/// matches the linked source.
pub(crate) fn file_origin(file_path: &str) -> ImportOrigin {
let path = std::path::Path::new(file_path);
let canonical = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
let label = canonical
.file_name()
.map(|name| name.to_string_lossy().to_string())
.unwrap_or_else(|| file_path.to_string());
ImportOrigin { origin: canonical.to_string_lossy().to_string(), label }
}
pub(crate) fn url_origin(url: &str) -> ImportOrigin {
ImportOrigin { origin: url.to_string(), label: url.to_string() }
}
pub(crate) fn commit_import<R: Runtime>(
window: &WebviewWindow<R>,
plan: ImportPlan,
) -> Result<BatchUpsertResult> {
Ok(import::commit_import_plan(&window.db_manager(), plan)?)
}
/// Download an importable document (OpenAPI, Postman, Insomnia, …) so it can be fed to the same /// Download an importable document (OpenAPI, Postman, Insomnia, …) so it can be fed to the same
/// pipeline as a file on disk. /// pipeline as a file on disk.
/// ///
@@ -79,7 +110,7 @@ async fn fetch_import_url<R: Runtime>(window: &WebviewWindow<R>, url: &str) -> R
.map_err(|err| Error::GenericError(format!("Failed to read response from {url}: {err}"))) .map_err(|err| Error::GenericError(format!("Failed to read response from {url}: {err}")))
} }
fn normalize_import_url(url: &str) -> Result<String> { pub(crate) fn normalize_import_url(url: &str) -> Result<String> {
let url = url.trim(); let url = url.trim();
if url.is_empty() { if url.is_empty() {
return Err(Error::GenericError("Import URL must not be empty".to_string())); return Err(Error::GenericError("Import URL must not be empty".to_string()));
+280 -229
View File
@@ -4,7 +4,7 @@ use crate::error::Error::GenericError;
use crate::error::Result; use crate::error::Result;
use crate::grpc::{build_metadata, metadata_to_map}; use crate::grpc::{build_metadata, metadata_to_map};
use crate::http_request::send_http_request; use crate::http_request::send_http_request;
use crate::import::{import_data, import_url}; use crate::import::{commit_import, plan_import_data, plan_import_url};
use crate::models_ext::{BlobManagerExt, QueryManagerExt}; use crate::models_ext::{BlobManagerExt, QueryManagerExt};
use crate::notifications::YaakNotifier; use crate::notifications::YaakNotifier;
use crate::render::{render_grpc_request, render_template}; use crate::render::{render_grpc_request, render_template};
@@ -40,12 +40,11 @@ use yaak_models::models::{
CookieJar, Environment, GrpcConnection, GrpcConnectionState, GrpcEvent, CookieJar, Environment, GrpcConnection, GrpcConnectionState, GrpcEvent,
GrpcEventType, HttpRequest, HttpResponse, HttpResponseState, Workspace, GrpcEventType, HttpRequest, HttpResponse, HttpResponseState, Workspace,
}; };
use yaak_models::util::{BatchUpsertResult, UpdateSource}; use yaak_models::util::{BatchUpsertResult, ImportDestination, ImportPlan, UpdateSource};
use yaak_plugins::events::{ use yaak_plugins::events::{
Color, ErrorResponse, FilterResponse, InternalEvent, InternalEventPayload, PluginContext, Color, ErrorResponse, FilterResponse, InternalEvent, InternalEventPayload, PluginContext,
RenderPurpose, ShowToastRequest, RenderPurpose, ShowToastRequest,
}; };
use yaak_plugins::manager::PluginManager;
use yaak_plugins::template_callback::PluginTemplateCallback; use yaak_plugins::template_callback::PluginTemplateCallback;
use yaak_rpc_schema::{AppMetaData, EphemeralHttpResponse}; use yaak_rpc_schema::{AppMetaData, EphemeralHttpResponse};
use yaak_sse::sse::ServerSentEvent; use yaak_sse::sse::ServerSentEvent;
@@ -238,19 +237,19 @@ async fn cmd_grpc_reflect<R: Runtime>(
app_handle: AppHandle<R>, app_handle: AppHandle<R>,
grpc_handle: State<'_, Mutex<GrpcHandle>>, grpc_handle: State<'_, Mutex<GrpcHandle>>,
) -> YaakResult<Vec<ServiceDefinition>> { ) -> YaakResult<Vec<ServiceDefinition>> {
let unrendered_request = app_handle.db().get_grpc_request(request_id)?; let unrendered_request = app_handle.db()?.get_grpc_request(request_id)?;
let (resolved_request, auth_context_id) = let (resolved_request, auth_context_id) =
resolve_grpc_request(&window.db(), &unrendered_request)?; resolve_grpc_request(&window.db()?, &unrendered_request)?;
let environment_chain = app_handle.db().resolve_environments( let environment_chain = app_handle.db()?.resolve_environments(
&unrendered_request.workspace_id, &unrendered_request.workspace_id,
unrendered_request.folder_id.as_deref(), unrendered_request.folder_id.as_deref(),
environment_id, environment_id,
)?; )?;
let resolved_settings = let resolved_settings =
app_handle.db().resolve_settings_for_grpc_request(&unrendered_request)?; app_handle.db()?.resolve_settings_for_grpc_request(&unrendered_request)?;
let plugin_manager = Arc::new((*app_handle.state::<PluginManager>()).clone()); let plugin_manager = Arc::new(crate::plugins_ext::plugin_manager(&app_handle).await?);
let encryption_manager = Arc::new((*app_handle.state::<EncryptionManager>()).clone()); let encryption_manager = Arc::new((*app_handle.state::<EncryptionManager>()).clone());
let req = render_grpc_request( let req = render_grpc_request(
&resolved_request, &resolved_request,
@@ -267,7 +266,7 @@ async fn cmd_grpc_reflect<R: Runtime>(
let uri = safe_uri(&req.url); let uri = safe_uri(&req.url);
let metadata = build_metadata(&window, &req, &auth_context_id).await?; let metadata = build_metadata(&window, &req, &auth_context_id).await?;
let settings = window.db().get_settings(); let settings = window.db()?.get_settings();
let client_certificate = let client_certificate =
find_client_certificate(req.url.as_str(), &settings.client_certificates); find_client_certificate(req.url.as_str(), &settings.client_certificates);
let proto_files: Vec<PathBuf> = let proto_files: Vec<PathBuf> =
@@ -299,18 +298,18 @@ async fn cmd_grpc_go<R: Runtime>(
window: WebviewWindow<R>, window: WebviewWindow<R>,
grpc_handle: State<'_, Mutex<GrpcHandle>>, grpc_handle: State<'_, Mutex<GrpcHandle>>,
) -> YaakResult<String> { ) -> YaakResult<String> {
let unrendered_request = app_handle.db().get_grpc_request(request_id)?; let unrendered_request = app_handle.db()?.get_grpc_request(request_id)?;
let (resolved_request, auth_context_id) = let (resolved_request, auth_context_id) =
resolve_grpc_request(&window.db(), &unrendered_request)?; resolve_grpc_request(&window.db()?, &unrendered_request)?;
let environment_chain = app_handle.db().resolve_environments( let environment_chain = app_handle.db()?.resolve_environments(
&unrendered_request.workspace_id, &unrendered_request.workspace_id,
unrendered_request.folder_id.as_deref(), unrendered_request.folder_id.as_deref(),
environment_id, environment_id,
)?; )?;
let resolved_settings = let resolved_settings =
app_handle.db().resolve_settings_for_grpc_request(&unrendered_request)?; app_handle.db()?.resolve_settings_for_grpc_request(&unrendered_request)?;
let plugin_manager = Arc::new((*app_handle.state::<PluginManager>()).clone()); let plugin_manager = Arc::new(crate::plugins_ext::plugin_manager(&app_handle).await?);
let encryption_manager = Arc::new((*app_handle.state::<EncryptionManager>()).clone()); let encryption_manager = Arc::new((*app_handle.state::<EncryptionManager>()).clone());
let request = render_grpc_request( let request = render_grpc_request(
&resolved_request, &resolved_request,
@@ -328,10 +327,10 @@ async fn cmd_grpc_go<R: Runtime>(
let metadata = build_metadata(&window, &request, &auth_context_id).await?; let metadata = build_metadata(&window, &request, &auth_context_id).await?;
// Find matching client certificate for this URL // Find matching client certificate for this URL
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.db()?.upsert_grpc_connection(
&GrpcConnection { &GrpcConnection {
workspace_id: request.workspace_id.clone(), workspace_id: request.workspace_id.clone(),
request_id: request.id.clone(), request_id: request.id.clone(),
@@ -387,7 +386,7 @@ 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.db()?.upsert_grpc_connection(
&GrpcConnection { &GrpcConnection {
elapsed: start.elapsed().as_millis() as i32, elapsed: start.elapsed().as_millis() as i32,
error: Some(err.to_string()), error: Some(err.to_string()),
@@ -496,7 +495,7 @@ 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.db()?.upsert_grpc_event(
&GrpcEvent { &GrpcEvent {
content: format!("Connecting to {}", req.url), content: format!("Connecting to {}", req.url),
event_type: GrpcEventType::ConnectionStart, event_type: GrpcEventType::ConnectionStart,
@@ -514,24 +513,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.db().and_then(|db| {
&GrpcEvent { db.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.db().and_then(|db| {
&GrpcEvent { db.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),
)
});
} }
} }
}; };
@@ -585,14 +588,16 @@ async fn cmd_grpc_go<R: Runtime>(
if !method_desc.is_client_streaming() { if !method_desc.is_client_streaming() {
app_handle app_handle
.db() .db()
.upsert_grpc_event( .and_then(|db| {
&GrpcEvent { db.upsert_grpc_event(
event_type: GrpcEventType::ClientMessage, &GrpcEvent {
content: msg, event_type: GrpcEventType::ClientMessage,
..base_event.clone() content: msg,
}, ..base_event.clone()
&UpdateSource::from_window_label(window.label()), },
) &UpdateSource::from_window_label(window.label()),
)
})
.unwrap(); .unwrap();
} }
@@ -600,20 +605,22 @@ async fn cmd_grpc_go<R: Runtime>(
Some(Ok(msg)) => { Some(Ok(msg)) => {
app_handle app_handle
.db() .db()
.upsert_grpc_event( .and_then(|db| {
&GrpcEvent { db.upsert_grpc_event(
metadata: metadata_to_map(msg.metadata().clone()), &GrpcEvent {
content: if msg.metadata().len() == 0 { metadata: metadata_to_map(msg.metadata().clone()),
"Received response" content: if msg.metadata().len() == 0 {
} else { "Received response"
"Received response with metadata" } else {
} "Received response with metadata"
.to_string(), }
event_type: GrpcEventType::Info, .to_string(),
..base_event.clone() event_type: GrpcEventType::Info,
}, ..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
@@ -624,82 +631,92 @@ async fn cmd_grpc_go<R: Runtime>(
Err(err) => { Err(err) => {
app_handle app_handle
.db() .db()
.upsert_grpc_event( .and_then(|db| {
&GrpcEvent { db.upsert_grpc_event(
content: "Failed to read response".to_string(), &GrpcEvent {
error: Some(err.to_string()), content: "Failed to read response".to_string(),
status: Some(Code::Internal as i32), error: Some(err.to_string()),
event_type: GrpcEventType::ConnectionEnd, status: Some(Code::Internal as i32),
..base_event.clone() event_type: GrpcEventType::ConnectionEnd,
}, ..base_event.clone()
&UpdateSource::from_window_label(window.label()), },
) &UpdateSource::from_window_label(window.label()),
)
})
.unwrap(); .unwrap();
return; return;
} }
}; };
app_handle app_handle
.db() .db()
.upsert_grpc_event( .and_then(|db| {
&GrpcEvent { db.upsert_grpc_event(
content, &GrpcEvent {
event_type: GrpcEventType::ServerMessage, content,
..base_event.clone() event_type: GrpcEventType::ServerMessage,
}, ..base_event.clone()
&UpdateSource::from_window_label(window.label()), },
) &UpdateSource::from_window_label(window.label()),
)
})
.unwrap(); .unwrap();
app_handle app_handle
.db() .db()
.upsert_grpc_event( .and_then(|db| {
&GrpcEvent { db.upsert_grpc_event(
content: "Connection complete".to_string(), &GrpcEvent {
event_type: GrpcEventType::ConnectionEnd, content: "Connection complete".to_string(),
status: Some(Code::Ok as i32), event_type: GrpcEventType::ConnectionEnd,
..base_event.clone() status: Some(Code::Ok as i32),
}, ..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() .db()
.upsert_grpc_event( .and_then(|db| {
&(match e.status { db.upsert_grpc_event(
Some(s) => GrpcEvent { &(match e.status {
error: Some(s.message().to_string()), Some(s) => GrpcEvent {
status: Some(s.code() as i32), error: Some(s.message().to_string()),
content: "Request failed".to_string(), status: Some(s.code() as i32),
metadata: metadata_to_map(s.metadata().clone()), content: "Request failed".to_string(),
event_type: GrpcEventType::ConnectionEnd, metadata: metadata_to_map(s.metadata().clone()),
..base_event.clone() event_type: GrpcEventType::ConnectionEnd,
}, ..base_event.clone()
None => GrpcEvent { },
error: Some(e.message), None => GrpcEvent {
status: Some(Code::Unknown as i32), error: Some(e.message),
content: "Request failed".to_string(), status: Some(Code::Unknown as i32),
event_type: GrpcEventType::ConnectionEnd, content: "Request failed".to_string(),
..base_event.clone() event_type: GrpcEventType::ConnectionEnd,
}, ..base_event.clone()
}), },
&UpdateSource::from_window_label(window.label()), }),
) &UpdateSource::from_window_label(window.label()),
)
})
.unwrap(); .unwrap();
} }
Some(Err(e)) => { Some(Err(e)) => {
app_handle app_handle
.db() .db()
.upsert_grpc_event( .and_then(|db| {
&GrpcEvent { db.upsert_grpc_event(
error: Some(e.to_string()), &GrpcEvent {
status: Some(Code::Unknown as i32), error: Some(e.to_string()),
content: "Request failed".to_string(), status: Some(Code::Unknown as i32),
event_type: GrpcEventType::ConnectionEnd, content: "Request failed".to_string(),
..base_event.clone() event_type: GrpcEventType::ConnectionEnd,
}, ..base_event.clone()
&UpdateSource::from_window_label(window.label()), },
) &UpdateSource::from_window_label(window.label()),
)
})
.unwrap(); .unwrap();
} }
None => { None => {
@@ -711,20 +728,22 @@ async fn cmd_grpc_go<R: Runtime>(
Some(Ok(stream)) => { Some(Ok(stream)) => {
app_handle app_handle
.db() .db()
.upsert_grpc_event( .and_then(|db| {
&GrpcEvent { db.upsert_grpc_event(
metadata: metadata_to_map(stream.metadata().clone()), &GrpcEvent {
content: if stream.metadata().len() == 0 { metadata: metadata_to_map(stream.metadata().clone()),
"Received response" content: if stream.metadata().len() == 0 {
} else { "Received response"
"Received response with metadata" } else {
} "Received response with metadata"
.to_string(), }
event_type: GrpcEventType::Info, .to_string(),
..base_event.clone() event_type: GrpcEventType::Info,
}, ..base_event.clone()
&UpdateSource::from_window_label(window.label()), },
) &UpdateSource::from_window_label(window.label()),
)
})
.unwrap(); .unwrap();
stream.into_inner() stream.into_inner()
} }
@@ -732,42 +751,46 @@ async fn cmd_grpc_go<R: Runtime>(
warn!("GRPC stream error {e:?}"); warn!("GRPC stream error {e:?}");
app_handle app_handle
.db() .db()
.upsert_grpc_event( .and_then(|db| {
&(match e.status { db.upsert_grpc_event(
Some(s) => GrpcEvent { &(match e.status {
error: Some(s.message().to_string()), Some(s) => GrpcEvent {
status: Some(s.code() as i32), error: Some(s.message().to_string()),
content: "Stream failed".to_string(), status: Some(s.code() as i32),
metadata: metadata_to_map(s.metadata().clone()), content: "Stream failed".to_string(),
event_type: GrpcEventType::ConnectionEnd, metadata: metadata_to_map(s.metadata().clone()),
..base_event.clone() event_type: GrpcEventType::ConnectionEnd,
}, ..base_event.clone()
None => GrpcEvent { },
error: Some(e.message), None => GrpcEvent {
status: Some(Code::Unknown as i32), error: Some(e.message),
content: "Stream failed".to_string(), status: Some(Code::Unknown as i32),
event_type: GrpcEventType::ConnectionEnd, content: "Stream failed".to_string(),
..base_event.clone() event_type: GrpcEventType::ConnectionEnd,
}, ..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() .db()
.upsert_grpc_event( .and_then(|db| {
&GrpcEvent { db.upsert_grpc_event(
error: Some(e.to_string()), &GrpcEvent {
status: Some(Code::Unknown as i32), error: Some(e.to_string()),
content: "Stream failed".to_string(), status: Some(Code::Unknown as i32),
event_type: GrpcEventType::ConnectionEnd, content: "Stream failed".to_string(),
..base_event.clone() event_type: GrpcEventType::ConnectionEnd,
}, ..base_event.clone()
&UpdateSource::from_window_label(window.label()), },
) &UpdateSource::from_window_label(window.label()),
)
})
.unwrap(); .unwrap();
return; return;
} }
@@ -785,30 +808,34 @@ async fn cmd_grpc_go<R: Runtime>(
Err(err) => { Err(err) => {
app_handle app_handle
.db() .db()
.upsert_grpc_event( .and_then(|db| {
&GrpcEvent { db.upsert_grpc_event(
content: "Failed to read response".to_string(), &GrpcEvent {
error: Some(err.to_string()), content: "Failed to read response".to_string(),
status: Some(Code::Internal as i32), error: Some(err.to_string()),
event_type: GrpcEventType::ConnectionEnd, status: Some(Code::Internal as i32),
..base_event.clone() event_type: GrpcEventType::ConnectionEnd,
}, ..base_event.clone()
&UpdateSource::from_window_label(window.label()), },
) &UpdateSource::from_window_label(window.label()),
)
})
.unwrap(); .unwrap();
break; break;
} }
}; };
app_handle app_handle
.db() .db()
.upsert_grpc_event( .and_then(|db| {
&GrpcEvent { db.upsert_grpc_event(
content: message, &GrpcEvent {
event_type: GrpcEventType::ServerMessage, content: message,
..base_event.clone() event_type: GrpcEventType::ServerMessage,
}, ..base_event.clone()
&UpdateSource::from_window_label(window.label()), },
) &UpdateSource::from_window_label(window.label()),
)
})
.unwrap(); .unwrap();
} }
Ok(None) => { Ok(None) => {
@@ -816,33 +843,37 @@ async fn cmd_grpc_go<R: Runtime>(
stream.trailers().await.unwrap_or_default().unwrap_or_default(); stream.trailers().await.unwrap_or_default().unwrap_or_default();
app_handle app_handle
.db() .db()
.upsert_grpc_event( .and_then(|db| {
&GrpcEvent { db.upsert_grpc_event(
content: "Connection complete".to_string(), &GrpcEvent {
status: Some(Code::Ok as i32), content: "Connection complete".to_string(),
metadata: metadata_to_map(trailers), status: Some(Code::Ok as i32),
event_type: GrpcEventType::ConnectionEnd, metadata: metadata_to_map(trailers),
..base_event.clone() event_type: GrpcEventType::ConnectionEnd,
}, ..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() .db()
.upsert_grpc_event( .and_then(|db| {
&GrpcEvent { db.upsert_grpc_event(
content: "Stream failed".to_string(), &GrpcEvent {
error: Some(status.message().to_string()), content: "Stream failed".to_string(),
status: Some(status.code() as i32), error: Some(status.message().to_string()),
metadata: metadata_to_map(status.metadata().clone()), status: Some(status.code() as i32),
event_type: GrpcEventType::ConnectionEnd, metadata: metadata_to_map(status.metadata().clone()),
..base_event.clone() event_type: GrpcEventType::ConnectionEnd,
}, ..base_event.clone()
&UpdateSource::from_window_label(window.label()), },
) &UpdateSource::from_window_label(window.label()),
)
})
.unwrap(); .unwrap();
break; break;
} }
@@ -857,7 +888,7 @@ async fn cmd_grpc_go<R: Runtime>(
let w = app_handle.clone(); let w = app_handle.clone();
tokio::select! { tokio::select! {
_ = grpc_listen => { _ = grpc_listen => {
let events = w.db().list_grpc_events(&conn_id).unwrap(); let events = w.db().and_then(|db| db.list_grpc_events(&conn_id)).unwrap();
let closed_event = events let closed_event = events
.iter() .iter()
.find(|e| GrpcEventType::ConnectionEnd == e.event_type); .find(|e| GrpcEventType::ConnectionEnd == e.event_type);
@@ -875,7 +906,7 @@ async fn cmd_grpc_go<R: Runtime>(
}).unwrap(); }).unwrap();
}, },
_ = cancelled_rx.changed() => { _ = cancelled_rx.changed() => {
w.db().upsert_grpc_event( w.db().and_then(|db| db.upsert_grpc_event(
&GrpcEvent { &GrpcEvent {
content: "Cancelled".to_string(), content: "Cancelled".to_string(),
event_type: GrpcEventType::ConnectionEnd, event_type: GrpcEventType::ConnectionEnd,
@@ -883,7 +914,7 @@ async fn cmd_grpc_go<R: Runtime>(
..base_msg.clone() ..base_msg.clone()
}, },
&UpdateSource::from_window_label(window.label()), &UpdateSource::from_window_label(window.label()),
).unwrap(); )).unwrap();
w.with_tx(|c| { w.with_tx(|c| {
c.upsert_grpc_connection( c.upsert_grpc_connection(
&GrpcConnection{ &GrpcConnection{
@@ -924,11 +955,11 @@ async fn cmd_send_ephemeral_request<R: Runtime>(
let response = HttpResponse::default(); let response = HttpResponse::default();
request.id = "".to_string(); request.id = "".to_string();
let environment = match environment_id { let environment = match environment_id {
Some(id) => Some(app_handle.db().get_environment(id)?), Some(id) => Some(app_handle.db()?.get_environment(id)?),
None => None, None => None,
}; };
let cookie_jar = match cookie_jar_id { let cookie_jar = match cookie_jar_id {
Some(id) => Some(app_handle.db().get_cookie_jar(id)?), Some(id) => Some(app_handle.db()?.get_cookie_jar(id)?),
None => None, None => None,
}; };
@@ -962,11 +993,10 @@ async fn cmd_format_graphql(text: &str) -> YaakResult<String> {
async fn cmd_http_response_body<R: Runtime>( async fn cmd_http_response_body<R: Runtime>(
window: WebviewWindow<R>, window: WebviewWindow<R>,
plugin_manager: State<'_, PluginManager>,
response_id: &str, response_id: &str,
filter: Option<&str>, filter: Option<&str>,
) -> YaakResult<FilterResponse> { ) -> YaakResult<FilterResponse> {
let location = locate_response_body(&window.db(), response_id)?; let location = locate_response_body(&window.db()?, response_id)?;
let Some(body_path) = location.path else { let Some(body_path) = location.path else {
return Ok(FilterResponse { content: String::new(), error: None }); return Ok(FilterResponse { content: String::new(), error: None });
}; };
@@ -977,7 +1007,8 @@ async fn cmd_http_response_body<R: Runtime>(
.ok_or(GenericError("Failed to find response body".to_string()))?; .ok_or(GenericError("Failed to find response body".to_string()))?;
match filter { match filter {
Some(filter) if !filter.is_empty() => Ok(plugin_manager Some(filter) if !filter.is_empty() => Ok(plugins_ext::plugin_manager(&window)
.await?
.filter_data(&window.plugin_context(), filter, &body, content_type) .filter_data(&window.plugin_context(), filter, &body, content_type)
.await?), .await?),
_ => Ok(FilterResponse { content: body, error: None }), _ => Ok(FilterResponse { content: body, error: None }),
@@ -988,7 +1019,7 @@ async fn cmd_get_sse_events<R: Runtime>(
app_handle: AppHandle<R>, app_handle: AppHandle<R>,
response_id: &str, response_id: &str,
) -> YaakResult<Vec<ServerSentEvent>> { ) -> YaakResult<Vec<ServerSentEvent>> {
let Some(body_path) = locate_response_body(&app_handle.db(), response_id)?.path else { let Some(body_path) = locate_response_body(&app_handle.db()?, response_id)?.path else {
return Ok(Vec::new()); return Ok(Vec::new());
}; };
@@ -1014,15 +1045,24 @@ async fn cmd_get_sse_events<R: Runtime>(
async fn cmd_import_data<R: Runtime>( async fn cmd_import_data<R: Runtime>(
window: WebviewWindow<R>, window: WebviewWindow<R>,
file_path: &str, file_path: &str,
) -> YaakResult<BatchUpsertResult> { destination: ImportDestination,
import_data(&window, file_path).await ) -> YaakResult<ImportPlan> {
plan_import_data(&window, file_path, destination).await
} }
async fn cmd_import_url<R: Runtime>( async fn cmd_import_url<R: Runtime>(
window: WebviewWindow<R>, window: WebviewWindow<R>,
url: &str, url: &str,
destination: ImportDestination,
) -> YaakResult<ImportPlan> {
plan_import_url(&window, url, destination).await
}
async fn cmd_commit_import<R: Runtime>(
window: WebviewWindow<R>,
plan: ImportPlan,
) -> YaakResult<BatchUpsertResult> { ) -> YaakResult<BatchUpsertResult> {
import_url(&window, url).await commit_import(&window, plan)
} }
@@ -1069,10 +1109,10 @@ async fn cmd_send_http_request<R: Runtime>(
cookie_jar_id: Option<&str>, cookie_jar_id: Option<&str>,
request_id: String, request_id: String,
) -> YaakResult<HttpResponse> { ) -> YaakResult<HttpResponse> {
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.db()?.upsert_http_response(
&HttpResponse { &HttpResponse {
request_id: request.id.clone(), request_id: request.id.clone(),
workspace_id: request.workspace_id.clone(), workspace_id: request.workspace_id.clone(),
@@ -1090,7 +1130,7 @@ async fn cmd_send_http_request<R: Runtime>(
}); });
let environment = match environment_id { let environment = match environment_id {
Some(id) => match app_handle.db().get_environment(id) { Some(id) => match app_handle.db()?.get_environment(id) {
Ok(env) => Some(env), Ok(env) => Some(env),
Err(e) => { Err(e) => {
warn!("Failed to find environment by id {id} {}", e); warn!("Failed to find environment by id {id} {}", e);
@@ -1101,7 +1141,7 @@ async fn cmd_send_http_request<R: Runtime>(
}; };
let cookie_jar = match cookie_jar_id { let cookie_jar = match cookie_jar_id {
Some(id) => Some(app_handle.db().get_cookie_jar(id)?), Some(id) => Some(app_handle.db()?.get_cookie_jar(id)?),
None => None, None => None,
}; };
@@ -1117,8 +1157,8 @@ 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.db()?.upsert_http_response(
&HttpResponse { &HttpResponse {
state: HttpResponseState::Closed, state: HttpResponseState::Closed,
error: Some(e.to_string()), error: Some(e.to_string()),
@@ -1141,7 +1181,7 @@ async fn cmd_new_child_window<R: Runtime>(
title: &str, title: &str,
inner_size: (f64, f64), inner_size: (f64, f64),
) -> YaakResult<()> { ) -> YaakResult<()> {
let use_native_titlebar = parent_window.app_handle().db().get_settings().use_native_titlebar; let use_native_titlebar = parent_window.app_handle().db()?.get_settings().use_native_titlebar;
let initialization_script = initial_appearance_script(&parent_window.app_handle()); let initialization_script = initial_appearance_script(&parent_window.app_handle());
let win = yaak_window::window::create_child_window( let win = yaak_window::window::create_child_window(
&parent_window, &parent_window,
@@ -1157,7 +1197,7 @@ async fn cmd_new_child_window<R: Runtime>(
} }
async fn cmd_new_main_window<R: Runtime>(app_handle: AppHandle<R>, url: &str) -> YaakResult<()> { async fn cmd_new_main_window<R: Runtime>(app_handle: AppHandle<R>, url: &str) -> YaakResult<()> {
let use_native_titlebar = app_handle.db().get_settings().use_native_titlebar; let use_native_titlebar = app_handle.db()?.get_settings().use_native_titlebar;
let initialization_script = initial_appearance_script(&app_handle); let initialization_script = initial_appearance_script(&app_handle);
let win = yaak_window::window::create_main_window( let win = yaak_window::window::create_main_window(
&app_handle, &app_handle,
@@ -1174,7 +1214,7 @@ async fn cmd_check_for_updates<R: Runtime>(
yaak_updater: State<'_, Mutex<YaakUpdater>>, yaak_updater: State<'_, Mutex<YaakUpdater>>,
) -> YaakResult<bool> { ) -> YaakResult<bool> {
let update_mode = get_update_mode(&window).await?; let update_mode = get_update_mode(&window).await?;
let settings = window.db().get_settings(); let settings = window.db()?.get_settings();
Ok(yaak_updater Ok(yaak_updater
.lock() .lock()
.await .await
@@ -1262,7 +1302,7 @@ pub fn run() {
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) =
yaak_lifecycle::on_launch(&lifecycle_host, &app.db(), &app.blob_manager()) yaak_lifecycle::on_launch(&lifecycle_host, &app.db()?, &app.blob_manager())
{ {
error!("on_launch hook failed: {e:?}"); error!("on_launch hook failed: {e:?}");
} }
@@ -1338,7 +1378,7 @@ pub fn run() {
app.manage(Mutex::new(ws_manager)); app.manage(Mutex::new(ws_manager));
// Specific settings // Specific settings
let settings = app.db().get_settings(); let settings = app.db()?.get_settings();
app.app_handle().set_native_titlebar(settings.use_native_titlebar); app.app_handle().set_native_titlebar(settings.use_native_titlebar);
monitor_plugin_events(&app.app_handle().clone()); monitor_plugin_events(&app.app_handle().clone());
@@ -1351,7 +1391,8 @@ pub fn run() {
.run(|app_handle, event| { .run(|app_handle, event| {
match event { match event {
RunEvent::Ready => { RunEvent::Ready => {
let use_native_titlebar = app_handle.db().get_settings().use_native_titlebar; let settings = app_handle.db().map(|db| db.get_settings()).unwrap_or_default();
let use_native_titlebar = settings.use_native_titlebar;
let initialization_script = initial_appearance_script(app_handle); let initialization_script = initial_appearance_script(app_handle);
if let Ok(win) = yaak_window::window::create_main_window( if let Ok(win) = yaak_window::window::create_main_window(
app_handle, app_handle,
@@ -1390,7 +1431,10 @@ pub fn run() {
let w = app_handle.get_webview_window(&label).unwrap(); let w = app_handle.get_webview_window(&label).unwrap();
let h = app_handle.clone(); let h = app_handle.clone();
tauri::async_runtime::spawn(async move { tauri::async_runtime::spawn(async move {
let settings = w.db().get_settings(); let Ok(settings) = w.db().map(|db| db.get_settings()) else {
warn!("Failed to read settings for update check");
return;
};
if settings.autoupdate { if settings.autoupdate {
time::sleep(Duration::from_secs(3)).await; // Wait a bit so it's not so jarring time::sleep(Duration::from_secs(3)).await; // Wait a bit so it's not so jarring
let val: State<'_, Mutex<YaakUpdater>> = h.state(); let val: State<'_, Mutex<YaakUpdater>> = h.state();
@@ -1426,7 +1470,7 @@ pub fn run() {
} }
async fn get_update_mode<R: Runtime>(window: &WebviewWindow<R>) -> YaakResult<UpdateMode> { async fn get_update_mode<R: Runtime>(window: &WebviewWindow<R>) -> YaakResult<UpdateMode> {
let settings = window.db().get_settings(); let settings = window.db()?.get_settings();
Ok(UpdateMode::new(settings.update_channel.as_str())) Ok(UpdateMode::new(settings.update_channel.as_str()))
} }
@@ -1441,7 +1485,10 @@ fn safe_uri(endpoint: &str) -> String {
fn monitor_plugin_events<R: Runtime>(app_handle: &AppHandle<R>) { fn monitor_plugin_events<R: Runtime>(app_handle: &AppHandle<R>) {
let app_handle = app_handle.clone(); let app_handle = app_handle.clone();
tauri::async_runtime::spawn(async move { tauri::async_runtime::spawn(async move {
let plugin_manager: State<'_, PluginManager> = app_handle.state(); let plugin_manager = match plugins_ext::plugin_manager(&app_handle).await {
Ok(pm) => pm,
Err(_) => return, // The runtime failed to boot; there are no events
};
let (rx_id, mut rx) = plugin_manager.subscribe("app").await; let (rx_id, mut rx) = plugin_manager.subscribe("app").await;
while let Some(event) = rx.recv().await { while let Some(event) = rx.recv().await {
@@ -1482,9 +1529,13 @@ fn monitor_plugin_events<R: Runtime>(app_handle: &AppHandle<R>) {
} }
}; };
let plugin_manager: State<'_, PluginManager> = app_handle.state(); match plugins_ext::plugin_manager(&app_handle).await {
if let Err(e) = plugin_manager.reply(&event, &ev).await { Ok(pm) => {
warn!("Failed to reply to plugin manager: {:?}", e) if let Err(e) = pm.reply(&event, &ev).await {
warn!("Failed to reply to plugin manager: {:?}", e)
}
}
Err(e) => warn!("Failed to get plugin manager for reply: {e:?}"),
} }
}); });
} }
@@ -1546,13 +1597,13 @@ fn get_window_from_plugin_context<R: Runtime>(
} }
fn workspace_from_window<R: Runtime>(window: &WebviewWindow<R>) -> Option<Workspace> { fn workspace_from_window<R: Runtime>(window: &WebviewWindow<R>) -> Option<Workspace> {
window.workspace_id().and_then(|id| window.db().get_workspace(&id).ok()) window.workspace_id().and_then(|id| window.db().and_then(|db| db.get_workspace(&id)).ok())
} }
fn environment_from_window<R: Runtime>(window: &WebviewWindow<R>) -> Option<Environment> { fn environment_from_window<R: Runtime>(window: &WebviewWindow<R>) -> Option<Environment> {
window.environment_id().and_then(|id| window.db().get_environment(&id).ok()) window.environment_id().and_then(|id| window.db().and_then(|db| db.get_environment(&id)).ok())
} }
fn cookie_jar_from_window<R: Runtime>(window: &WebviewWindow<R>) -> Option<CookieJar> { fn cookie_jar_from_window<R: Runtime>(window: &WebviewWindow<R>) -> Option<CookieJar> {
window.cookie_jar_id().and_then(|id| window.db().get_cookie_jar(&id).ok()) window.cookie_jar_id().and_then(|id| window.db().and_then(|db| db.get_cookie_jar(&id)).ok())
} }
@@ -37,11 +37,9 @@ fn drain_model_changes_batch<R: Runtime>(
app_handle: &tauri::AppHandle<R>, app_handle: &tauri::AppHandle<R>,
cursor: &mut ModelChangeCursor, cursor: &mut ModelChangeCursor,
) -> bool { ) -> bool {
let changes = match query_manager.connect().list_model_changes_since( let changes = match query_manager.connect().and_then(|db| {
&cursor.created_at, db.list_model_changes_since(&cursor.created_at, cursor.id, MODEL_CHANGES_POLL_BATCH_SIZE)
cursor.id, }) {
MODEL_CHANGES_POLL_BATCH_SIZE,
) {
Ok(changes) => changes, Ok(changes) => changes,
Err(err) => { Err(err) => {
error!("Failed to poll model_changes rows: {err:?}"); error!("Failed to poll model_changes rows: {err:?}");
@@ -92,7 +90,7 @@ async fn run_model_change_poller<R: Runtime>(
/// Extension trait for accessing the QueryManager from Tauri Manager types. /// Extension trait for accessing the QueryManager from Tauri Manager types.
pub trait QueryManagerExt<'a, R> { pub trait QueryManagerExt<'a, R> {
fn db_manager(&'a self) -> State<'a, QueryManager>; fn db_manager(&'a self) -> State<'a, QueryManager>;
fn db(&'a self) -> ClientDb<'a>; fn db(&'a self) -> Result<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(&ClientDb) -> Result<T>;
@@ -103,7 +101,7 @@ impl<'a, R: Runtime, M: Manager<R>> QueryManagerExt<'a, R> for M {
self.state::<QueryManager>() self.state::<QueryManager>()
} }
fn db(&'a self) -> ClientDb<'a> { fn db(&'a self) -> Result<ClientDb<'a>> {
let qm = self.state::<QueryManager>(); let qm = self.state::<QueryManager>();
qm.inner().connect() qm.inner().connect()
} }
@@ -55,7 +55,7 @@ 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.db()?.set_key_value_raw(
KV_NAMESPACE, KV_NAMESPACE,
KV_KEY, KV_KEY,
seen_json.as_str(), seen_json.as_str(),
@@ -74,7 +74,7 @@ impl YaakNotifier {
self.last_check = Some(Instant::now()); self.last_check = Some(Instant::now());
if !app_handle.db().get_settings().check_notifications { if !app_handle.db()?.get_settings().check_notifications {
info!("Notifications are disabled. Skipping check."); info!("Notifications are disabled. Skipping check.");
return Ok(()); return Ok(());
} }
@@ -139,7 +139,7 @@ impl YaakNotifier {
} }
async fn get_kv<R: Runtime>(app_handle: &AppHandle<R>) -> Result<Vec<String>> { async fn get_kv<R: Runtime>(app_handle: &AppHandle<R>) -> Result<Vec<String>> {
match app_handle.db().get_key_value_raw("notifications", "seen") { match app_handle.db()?.get_key_value_raw("notifications", "seen") {
None => Ok(Vec::new()), None => Ok(Vec::new()),
Some(v) => Ok(serde_json::from_str(&v.value)?), Some(v) => Ok(serde_json::from_str(&v.value)?),
} }
@@ -155,7 +155,7 @@ fn get_updater_status<R: Runtime>(app_handle: &AppHandle<R>) -> &'static str {
#[cfg(all(feature = "updater", target_os = "linux"))] #[cfg(all(feature = "updater", target_os = "linux"))]
{ {
let settings = app_handle.db().get_settings(); let settings = app_handle.db()?.get_settings();
if !settings.autoupdate { if !settings.autoupdate {
// Updates are explicitly disabled // Updates are explicitly disabled
"disabled" "disabled"
@@ -170,7 +170,7 @@ fn get_updater_status<R: Runtime>(app_handle: &AppHandle<R>) -> &'static str {
#[cfg(all(feature = "updater", not(target_os = "linux")))] #[cfg(all(feature = "updater", not(target_os = "linux")))]
{ {
let settings = app_handle.db().get_settings(); let settings = app_handle.db()?.get_settings();
if settings.autoupdate { "enabled" } else { "disabled" } if settings.autoupdate { "enabled" } else { "disabled" }
} }
} }
@@ -32,7 +32,6 @@ use yaak_plugins::events::{
ShowToastRequest, TemplateRenderResponse, WindowInfoResponse, WindowNavigateEvent, ShowToastRequest, TemplateRenderResponse, WindowInfoResponse, WindowNavigateEvent,
WorkspaceInfo, WorkspaceInfo,
}; };
use yaak_plugins::manager::PluginManager;
use yaak_plugins::plugin_handle::PluginHandle; use yaak_plugins::plugin_handle::PluginHandle;
use yaak_plugins::template_callback::PluginTemplateCallback; use yaak_plugins::template_callback::PluginTemplateCallback;
use yaak_tauri_utils::window::WorkspaceWindowTrait; use yaak_tauri_utils::window::WorkspaceWindowTrait;
@@ -105,14 +104,14 @@ async fn handle_host_plugin_request<R: Runtime>(
Box::pin(handle_plugin_event(app_handle, &toast_event, plugin_handle)).await Box::pin(handle_plugin_event(app_handle, &toast_event, plugin_handle)).await
} }
HostRequest::ReloadResponse(req) => { HostRequest::ReloadResponse(req) => {
let plugins = app_handle.db().list_plugins()?; let plugins = app_handle.db()?.list_plugins()?;
for plugin in plugins { for plugin in plugins {
if plugin.directory != plugin_handle.dir { if plugin.directory != plugin_handle.dir {
continue; continue;
} }
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.db()?.upsert_plugin(&new_plugin, &UpdateSource::Plugin)?;
} }
if !req.silent { if !req.silent {
@@ -200,12 +199,12 @@ async fn handle_host_plugin_request<R: Runtime>(
let workspace = let workspace =
workspace_from_window(&window).expect("Failed to get workspace_id from window URL"); workspace_from_window(&window).expect("Failed to get workspace_id from window URL");
let environment_id = environment_from_window(&window).map(|e| e.id); let environment_id = environment_from_window(&window).map(|e| e.id);
let environment_chain = window.db().resolve_environments( let environment_chain = window.db()?.resolve_environments(
&workspace.id, &workspace.id,
req.grpc_request.folder_id.as_deref(), req.grpc_request.folder_id.as_deref(),
environment_id.as_deref(), environment_id.as_deref(),
)?; )?;
let plugin_manager = Arc::new((*app_handle.state::<PluginManager>()).clone()); let plugin_manager = Arc::new(crate::plugins_ext::plugin_manager(app_handle).await?);
let encryption_manager = Arc::new((*app_handle.state::<EncryptionManager>()).clone()); let encryption_manager = Arc::new((*app_handle.state::<EncryptionManager>()).clone());
let cb = PluginTemplateCallback::new( let cb = PluginTemplateCallback::new(
plugin_manager, plugin_manager,
@@ -226,12 +225,12 @@ async fn handle_host_plugin_request<R: Runtime>(
let workspace = let workspace =
workspace_from_window(&window).expect("Failed to get workspace_id from window URL"); workspace_from_window(&window).expect("Failed to get workspace_id from window URL");
let environment_id = environment_from_window(&window).map(|e| e.id); let environment_id = environment_from_window(&window).map(|e| e.id);
let environment_chain = window.db().resolve_environments( let environment_chain = window.db()?.resolve_environments(
&workspace.id, &workspace.id,
req.http_request.folder_id.as_deref(), req.http_request.folder_id.as_deref(),
environment_id.as_deref(), environment_id.as_deref(),
)?; )?;
let plugin_manager = Arc::new((*app_handle.state::<PluginManager>()).clone()); let plugin_manager = Arc::new(crate::plugins_ext::plugin_manager(app_handle).await?);
let encryption_manager = Arc::new((*app_handle.state::<EncryptionManager>()).clone()); let encryption_manager = Arc::new((*app_handle.state::<EncryptionManager>()).clone());
let cb = PluginTemplateCallback::new( let cb = PluginTemplateCallback::new(
plugin_manager, plugin_manager,
@@ -253,7 +252,7 @@ async fn handle_host_plugin_request<R: Runtime>(
workspace_from_window(&window).expect("Failed to get workspace_id from window URL"); workspace_from_window(&window).expect("Failed to get workspace_id from window URL");
let environment_id = environment_from_window(&window).map(|e| e.id); let environment_id = environment_from_window(&window).map(|e| e.id);
let folder_id = if let Some(id) = window.request_id() { let folder_id = if let Some(id) = window.request_id() {
match window.db().get_any_request(&id) { match window.db()?.get_any_request(&id) {
Ok(AnyRequest::HttpRequest(r)) => r.folder_id, Ok(AnyRequest::HttpRequest(r)) => r.folder_id,
Ok(AnyRequest::GrpcRequest(r)) => r.folder_id, Ok(AnyRequest::GrpcRequest(r)) => r.folder_id,
Ok(AnyRequest::WebsocketRequest(r)) => r.folder_id, Ok(AnyRequest::WebsocketRequest(r)) => r.folder_id,
@@ -262,12 +261,12 @@ async fn handle_host_plugin_request<R: Runtime>(
} else { } else {
None None
}; };
let environment_chain = window.db().resolve_environments( let environment_chain = window.db()?.resolve_environments(
&workspace.id, &workspace.id,
folder_id.as_deref(), folder_id.as_deref(),
environment_id.as_deref(), environment_id.as_deref(),
)?; )?;
let plugin_manager = Arc::new((*app_handle.state::<PluginManager>()).clone()); let plugin_manager = Arc::new(crate::plugins_ext::plugin_manager(app_handle).await?);
let encryption_manager = Arc::new((*app_handle.state::<EncryptionManager>()).clone()); let encryption_manager = Arc::new((*app_handle.state::<EncryptionManager>()).clone());
let cb = PluginTemplateCallback::new( let cb = PluginTemplateCallback::new(
plugin_manager, plugin_manager,
@@ -295,7 +294,7 @@ 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.db()?.upsert_http_response(
&HttpResponse { &HttpResponse {
request_id: http_request.id.clone(), request_id: http_request.id.clone(),
workspace_id: http_request.workspace_id.clone(), workspace_id: http_request.workspace_id.clone(),
@@ -329,7 +328,7 @@ async fn handle_host_plugin_request<R: Runtime>(
HostRequest::OpenWindow(req) => { HostRequest::OpenWindow(req) => {
let (navigation_tx, mut navigation_rx) = tokio::sync::mpsc::channel(128); let (navigation_tx, mut navigation_rx) = tokio::sync::mpsc::channel(128);
let (close_tx, mut close_rx) = tokio::sync::mpsc::channel(128); let (close_tx, mut close_rx) = tokio::sync::mpsc::channel(128);
let use_native_titlebar = app_handle.db().get_settings().use_native_titlebar; let use_native_titlebar = app_handle.db()?.get_settings().use_native_titlebar;
let win_config = CreateWindowConfig { let win_config = CreateWindowConfig {
url: &req.url, url: &req.url,
label: &req.label, label: &req.label,
@@ -439,7 +438,7 @@ async fn handle_host_plugin_request<R: Runtime>(
let environment_id = environment_from_window(&w).map(|m| m.id); let environment_id = environment_from_window(&w).map(|m| m.id);
let workspace_id = workspace_from_window(&w).map(|m| m.id); let workspace_id = workspace_from_window(&w).map(|m| m.id);
let request_id = let request_id =
match app_handle.db().get_any_request(&w.request_id().unwrap_or_default()) { match app_handle.db()?.get_any_request(&w.request_id().unwrap_or_default()) {
Ok(AnyRequest::HttpRequest(r)) => Some(r.id), Ok(AnyRequest::HttpRequest(r)) => Some(r.id),
Ok(AnyRequest::WebsocketRequest(r)) => Some(r.id), Ok(AnyRequest::WebsocketRequest(r)) => Some(r.id),
Ok(AnyRequest::GrpcRequest(r)) => Some(r.id), Ok(AnyRequest::GrpcRequest(r)) => Some(r.id),
+81 -22
View File
@@ -31,10 +31,43 @@ use yaak_plugins::api::{
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);
// ============================================================================
// Plugin Manager Handle
// ============================================================================
/// The plugin runtime boots in the background so startup doesn't wait on it.
/// This handle is the only way to reach the manager: [`PluginManagerHandle::get`]
/// resolves once boot completes, so callers can never observe a
/// partially-initialized runtime.
#[derive(Clone)]
pub struct PluginManagerHandle {
rx: tokio::sync::watch::Receiver<Option<std::result::Result<PluginManager, String>>>,
}
impl PluginManagerHandle {
pub async fn get(&self) -> yaak_plugins::error::Result<PluginManager> {
let mut rx = self.rx.clone();
let result = rx
.wait_for(|v| v.is_some())
.await
.map_err(|_| PluginErr("Plugin runtime boot task died".to_string()))?;
result.clone().unwrap().map_err(PluginErr)
}
}
/// Wait for the plugin runtime to finish booting and return the manager.
pub async fn plugin_manager<R: Runtime>(
manager: &impl Manager<R>,
) -> yaak_plugins::error::Result<PluginManager> {
let handle = manager.state::<PluginManagerHandle>().inner().clone();
handle.get().await
}
// ============================================================================ // ============================================================================
// Plugin Updater // Plugin Updater
// ============================================================================ // ============================================================================
@@ -74,7 +107,7 @@ impl PluginUpdater {
let app_version = window.app_handle().package_info().version.to_string(); let app_version = window.app_handle().package_info().version.to_string();
let http_client = yaak_api_client(ApiClientKind::App, &app_version)?; let http_client = yaak_api_client(ApiClientKind::App, &app_version)?;
let plugins = window.app_handle().db().list_plugins()?; let plugins = window.app_handle().db()?.list_plugins()?;
let updates = check_plugin_updates(&http_client, plugins.clone()).await?; let updates = check_plugin_updates(&http_client, plugins.clone()).await?;
if updates.plugins.is_empty() { if updates.plugins.is_empty() {
@@ -146,7 +179,7 @@ pub async fn cmd_plugins_install<R: Runtime>(
name: &str, name: &str,
version: Option<String>, version: Option<String>,
) -> Result<()> { ) -> Result<()> {
let plugin_manager = Arc::new((*window.state::<PluginManager>()).clone()); let plugin_manager = Arc::new(plugin_manager(&window).await?);
let app_version = window.app_handle().package_info().version.to_string(); let app_version = window.app_handle().package_info().version.to_string();
let http_client = yaak_api_client(ApiClientKind::App, &app_version)?; let http_client = yaak_api_client(ApiClientKind::App, &app_version)?;
let query_manager = window.state::<yaak_models::query_manager::QueryManager>(); let query_manager = window.state::<yaak_models::query_manager::QueryManager>();
@@ -167,7 +200,10 @@ pub async fn cmd_plugins_install_from_directory<R: Runtime>(
window: WebviewWindow<R>, window: WebviewWindow<R>,
directory: &str, directory: &str,
) -> Result<Plugin> { ) -> Result<Plugin> {
let plugin = window.db().upsert_plugin( // Resolve the manager before writing the row so startup's plugin snapshot
// can't include it and boot it a second time
let plugin_manager = Arc::new(plugin_manager(&window).await?);
let plugin = window.db()?.upsert_plugin(
&Plugin { &Plugin {
directory: directory.into(), directory: directory.into(),
url: None, url: None,
@@ -178,7 +214,6 @@ pub async fn cmd_plugins_install_from_directory<R: Runtime>(
&UpdateSource::from_window_label(window.label()), &UpdateSource::from_window_label(window.label()),
)?; )?;
let plugin_manager = Arc::new((*window.state::<PluginManager>()).clone());
plugin_manager.add_plugin(&window.plugin_context(), &plugin).await?; plugin_manager.add_plugin(&window.plugin_context(), &plugin).await?;
Ok(plugin) Ok(plugin)
@@ -188,7 +223,7 @@ pub async fn cmd_plugins_uninstall<R: Runtime>(
plugin_id: &str, plugin_id: &str,
window: WebviewWindow<R>, window: WebviewWindow<R>,
) -> Result<Plugin> { ) -> Result<Plugin> {
let plugin_manager = Arc::new((*window.state::<PluginManager>()).clone()); let plugin_manager = Arc::new(plugin_manager(&window).await?);
let query_manager = window.state::<yaak_models::query_manager::QueryManager>(); let query_manager = window.state::<yaak_models::query_manager::QueryManager>();
let plugin_context = window.plugin_context(); let plugin_context = window.plugin_context();
Ok(delete_and_uninstall(plugin_manager, &query_manager, &plugin_context, plugin_id).await?) Ok(delete_and_uninstall(plugin_manager, &query_manager, &plugin_context, plugin_id).await?)
@@ -199,7 +234,7 @@ pub async fn cmd_plugins_updates<R: Runtime>(
) -> Result<PluginUpdatesResponse> { ) -> Result<PluginUpdatesResponse> {
let app_version = app_handle.package_info().version.to_string(); let app_version = app_handle.package_info().version.to_string();
let http_client = yaak_api_client(ApiClientKind::App, &app_version)?; let http_client = yaak_api_client(ApiClientKind::App, &app_version)?;
let plugins = app_handle.db().list_plugins()?; let plugins = app_handle.db()?.list_plugins()?;
Ok(check_plugin_updates(&http_client, plugins).await?) Ok(check_plugin_updates(&http_client, plugins).await?)
} }
@@ -208,7 +243,7 @@ pub async fn cmd_plugins_update_all<R: Runtime>(
) -> Result<Vec<PluginNameVersion>> { ) -> Result<Vec<PluginNameVersion>> {
let app_version = window.app_handle().package_info().version.to_string(); let app_version = window.app_handle().package_info().version.to_string();
let http_client = yaak_api_client(ApiClientKind::App, &app_version)?; let http_client = yaak_api_client(ApiClientKind::App, &app_version)?;
let plugins = window.db().list_plugins()?; let plugins = window.db()?.list_plugins()?;
// Get list of available updates (already filtered to only registry plugins) // Get list of available updates (already filtered to only registry plugins)
let updates = check_plugin_updates(&http_client, plugins).await?; let updates = check_plugin_updates(&http_client, plugins).await?;
@@ -217,7 +252,7 @@ pub async fn cmd_plugins_update_all<R: Runtime>(
return Ok(Vec::new()); return Ok(Vec::new());
} }
let plugin_manager = Arc::new((*window.state::<PluginManager>()).clone()); let plugin_manager = Arc::new(plugin_manager(&window).await?);
let query_manager = window.state::<yaak_models::query_manager::QueryManager>(); let query_manager = window.state::<yaak_models::query_manager::QueryManager>();
let plugin_context = window.plugin_context(); let plugin_context = window.plugin_context();
@@ -300,20 +335,38 @@ pub fn init<R: Runtime>() -> TauriPlugin<R> {
let query_manager = let query_manager =
app_handle.state::<yaak_models::query_manager::QueryManager>().inner().clone(); app_handle.state::<yaak_models::query_manager::QueryManager>().inner().clone();
// Create plugin manager asynchronously // Boot the plugin runtime in the background so the window shows
// immediately. Everything that needs plugins resolves the handle,
// which waits for this task to finish.
let (tx, rx) = tokio::sync::watch::channel(None);
app_handle.manage(PluginManagerHandle { rx });
let app_handle_clone = app_handle.clone(); let app_handle_clone = app_handle.clone();
tauri::async_runtime::block_on(async move { tauri::async_runtime::spawn(async move {
let manager = PluginManager::new( let result = tokio::time::timeout(
vendored_plugin_dir, Duration::from_secs(60),
installed_plugin_dir, PluginManager::new(
node_bin_path, vendored_plugin_dir,
plugin_runtime_main, installed_plugin_dir,
&query_manager, node_bin_path,
&PluginContext::new_empty(), plugin_runtime_main,
dev_mode, &query_manager,
&PluginContext::new_empty(),
dev_mode,
),
) )
.await .await
.expect("Failed to start plugin runtime"); .unwrap_or_else(|_| Err(yaak_plugins::error::Error::PluginErr(
"Timed out starting the plugin runtime".to_string(),
)));
let manager = match result {
Ok(manager) => manager,
Err(e) => {
error!("Failed to start plugin runtime: {e:?}");
let _ = tx.send(Some(Err(e.to_string())));
return;
}
};
// Surface unexpected runtime crashes to the user // Surface unexpected runtime crashes to the user
let mut crash_rx = manager.runtime_crash_rx(); let mut crash_rx = manager.runtime_crash_rx();
@@ -339,7 +392,7 @@ pub fn init<R: Runtime>() -> TauriPlugin<R> {
} }
}); });
app_handle_clone.manage(manager); let _ = tx.send(Some(Ok(manager)));
}); });
let plugin_updater = PluginUpdater::new(); let plugin_updater = PluginUpdater::new();
@@ -355,8 +408,14 @@ pub fn init<R: Runtime>() -> TauriPlugin<R> {
api.prevent_exit(); api.prevent_exit();
tauri::async_runtime::block_on(async move { tauri::async_runtime::block_on(async move {
info!("Exiting plugin runtime due to app exit"); info!("Exiting plugin runtime due to app exit");
let manager: State<PluginManager> = app.state(); // Bound the wait in case the exit comes while boot is still
manager.terminate().await; // in flight
let get_manager = plugin_manager(app);
if let Ok(Ok(manager)) =
tokio::time::timeout(Duration::from_secs(5), get_manager).await
{
manager.terminate().await;
}
app.exit(0); app.exit(0);
}); });
} }
+84 -51
View File
@@ -37,30 +37,31 @@ use yaak_grpc::ServiceDefinition;
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,
HttpResponseEvent, Plugin, Settings, WebsocketConnection, WebsocketEvent, WorkspaceMeta, HttpResponseEvent, ImportSource, Plugin, Settings, WebsocketConnection, WebsocketEvent,
WorkspaceMeta,
}; };
use yaak_models::query_manager::QueryManager; use yaak_models::query_manager::QueryManager;
use yaak_models::util::BatchUpsertResult; 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.
@@ -109,10 +110,11 @@ impl<R: Runtime> Host for ClientCtx<R> {
} }
impl<R: Runtime> ClientCtx<R> { impl<R: Runtime> ClientCtx<R> {
/// The plugin runtime this window talks to. Only the `PluginHost` impl /// The plugin runtime this window talks to, once it finishes booting.
/// below uses it; everything else goes through the trait. /// Only the `PluginHost` impl below uses it; everything else goes through
fn pm(&self) -> State<'_, PluginManager> { /// the trait.
self.window.state::<PluginManager>() async fn pm(&self) -> yaak_plugins::error::Result<PluginManager> {
crate::plugins_ext::plugin_manager(&self.window).await
} }
} }
@@ -122,35 +124,40 @@ impl<R: Runtime> ClientCtx<R> {
/// providing them. /// providing them.
impl<R: Runtime> PluginHost for ClientCtx<R> { impl<R: Runtime> PluginHost for ClientCtx<R> {
async fn loaded_plugin_metadata(&self, directory: &str) -> Option<PluginMetadata> { async fn loaded_plugin_metadata(&self, directory: &str) -> Option<PluginMetadata> {
let handle = self.pm().get_plugin_by_dir(directory).await?; let handle = self.pm().await.ok()?.get_plugin_by_dir(directory).await?;
Some(handle.info()) Some(handle.info())
} }
async fn take_plugin_init_errors(&self) -> Vec<(String, String)> { async fn take_plugin_init_errors(&self) -> Vec<(String, String)> {
self.pm().take_init_errors().await match self.pm().await {
Ok(pm) => pm.take_init_errors().await,
Err(_) => Vec::new(),
}
} }
async fn resolve_plugins(&self, plugins: Vec<Plugin>) -> Vec<Plugin> { async fn resolve_plugins(&self, plugins: Vec<Plugin>) -> Vec<Plugin> {
self.pm().resolve_plugins_for_runtime_from_db(plugins).await match self.pm().await {
Ok(pm) => pm.resolve_plugins_for_runtime_from_db(plugins).await,
Err(_) => plugins,
}
} }
fn template_callback(&self, purpose: RenderPurpose) -> impl TemplateCallback { async fn template_callback(
PluginTemplateCallback::new( &self,
Arc::new((*self.pm()).clone()), purpose: RenderPurpose,
) -> yaak_commands::Result<impl TemplateCallback> {
Ok(PluginTemplateCallback::new(
Arc::new(self.pm().await?),
Arc::new(self.encryption_manager().clone()), Arc::new(self.encryption_manager().clone()),
&self.plugin_context(), &self.plugin_context(),
purpose, purpose,
) ))
} }
async fn template_function_summaries( async fn template_function_summaries(
&self, &self,
) -> yaak_commands::Result<Vec<GetTemplateFunctionSummaryResponse>> { ) -> yaak_commands::Result<Vec<GetTemplateFunctionSummaryResponse>> {
Ok(self Ok(self.pm().await?.get_template_function_summaries(&self.plugin_context()).await?)
.window
.state::<PluginManager>()
.get_template_function_summaries(&self.plugin_context())
.await?)
} }
async fn template_function_config( async fn template_function_config(
@@ -160,81 +167,81 @@ impl<R: Runtime> PluginHost for ClientCtx<R> {
model_id: &str, model_id: &str,
) -> yaak_commands::Result<GetTemplateFunctionConfigResponse> { ) -> yaak_commands::Result<GetTemplateFunctionConfigResponse> {
Ok(self Ok(self
.window .pm()
.state::<PluginManager>() .await?
.get_template_function_config(&self.plugin_context(), function_name, values, model_id) .get_template_function_config(&self.plugin_context(), function_name, values, model_id)
.await?) .await?)
} }
async fn themes(&self) -> yaak_commands::Result<Vec<GetThemesResponse>> { async fn themes(&self) -> yaak_commands::Result<Vec<GetThemesResponse>> {
Ok(self.pm().get_themes(&self.plugin_context()).await?) Ok(self.pm().await?.get_themes(&self.plugin_context()).await?)
} }
async fn http_request_actions( async fn http_request_actions(
&self, &self,
) -> yaak_commands::Result<Vec<GetHttpRequestActionsResponse>> { ) -> yaak_commands::Result<Vec<GetHttpRequestActionsResponse>> {
Ok(self.pm().get_http_request_actions(&self.plugin_context()).await?) Ok(self.pm().await?.get_http_request_actions(&self.plugin_context()).await?)
} }
async fn websocket_request_actions( async fn websocket_request_actions(
&self, &self,
) -> yaak_commands::Result<Vec<GetWebsocketRequestActionsResponse>> { ) -> yaak_commands::Result<Vec<GetWebsocketRequestActionsResponse>> {
Ok(self.pm().get_websocket_request_actions(&self.plugin_context()).await?) Ok(self.pm().await?.get_websocket_request_actions(&self.plugin_context()).await?)
} }
async fn grpc_request_actions( async fn grpc_request_actions(
&self, &self,
) -> yaak_commands::Result<Vec<GetGrpcRequestActionsResponse>> { ) -> yaak_commands::Result<Vec<GetGrpcRequestActionsResponse>> {
Ok(self.pm().get_grpc_request_actions(&self.plugin_context()).await?) Ok(self.pm().await?.get_grpc_request_actions(&self.plugin_context()).await?)
} }
async fn workspace_actions(&self) -> yaak_commands::Result<Vec<GetWorkspaceActionsResponse>> { async fn workspace_actions(&self) -> yaak_commands::Result<Vec<GetWorkspaceActionsResponse>> {
Ok(self.pm().get_workspace_actions(&self.plugin_context()).await?) Ok(self.pm().await?.get_workspace_actions(&self.plugin_context()).await?)
} }
async fn folder_actions(&self) -> yaak_commands::Result<Vec<GetFolderActionsResponse>> { async fn folder_actions(&self) -> yaak_commands::Result<Vec<GetFolderActionsResponse>> {
Ok(self.pm().get_folder_actions(&self.plugin_context()).await?) Ok(self.pm().await?.get_folder_actions(&self.plugin_context()).await?)
} }
async fn call_http_request_action( async fn call_http_request_action(
&self, &self,
req: CallHttpRequestActionRequest, req: CallHttpRequestActionRequest,
) -> yaak_commands::Result<()> { ) -> yaak_commands::Result<()> {
Ok(self.pm().call_http_request_action(&self.plugin_context(), req).await?) Ok(self.pm().await?.call_http_request_action(&self.plugin_context(), req).await?)
} }
async fn call_grpc_request_action( async fn call_grpc_request_action(
&self, &self,
req: CallGrpcRequestActionRequest, req: CallGrpcRequestActionRequest,
) -> yaak_commands::Result<()> { ) -> yaak_commands::Result<()> {
Ok(self.pm().call_grpc_request_action(&self.plugin_context(), req).await?) Ok(self.pm().await?.call_grpc_request_action(&self.plugin_context(), req).await?)
} }
async fn call_websocket_request_action( async fn call_websocket_request_action(
&self, &self,
req: CallWebsocketRequestActionRequest, req: CallWebsocketRequestActionRequest,
) -> yaak_commands::Result<()> { ) -> yaak_commands::Result<()> {
Ok(self.pm().call_websocket_request_action(&self.plugin_context(), req).await?) Ok(self.pm().await?.call_websocket_request_action(&self.plugin_context(), req).await?)
} }
async fn call_workspace_action( async fn call_workspace_action(
&self, &self,
req: CallWorkspaceActionRequest, req: CallWorkspaceActionRequest,
) -> yaak_commands::Result<()> { ) -> yaak_commands::Result<()> {
Ok(self.pm().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, &self,
req: CallFolderActionRequest, req: CallFolderActionRequest,
) -> yaak_commands::Result<()> { ) -> yaak_commands::Result<()> {
Ok(self.pm().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().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())
} }
@@ -246,6 +253,7 @@ impl<R: Runtime> PluginHost for ClientCtx<R> {
) -> yaak_commands::Result<GetHttpAuthenticationConfigResponse> { ) -> yaak_commands::Result<GetHttpAuthenticationConfigResponse> {
Ok(self Ok(self
.pm() .pm()
.await?
.get_http_authentication_config(&self.plugin_context(), auth_name, values, model_id) .get_http_authentication_config(&self.plugin_context(), auth_name, values, model_id)
.await?) .await?)
} }
@@ -259,6 +267,7 @@ impl<R: Runtime> PluginHost for ClientCtx<R> {
) -> yaak_commands::Result<()> { ) -> yaak_commands::Result<()> {
Ok(self Ok(self
.pm() .pm()
.await?
.call_http_authentication_action( .call_http_authentication_action(
&self.plugin_context(), &self.plugin_context(),
auth_name, auth_name,
@@ -270,15 +279,18 @@ impl<R: Runtime> PluginHost for ClientCtx<R> {
} }
async fn import_data(&self, content: &str) -> yaak_commands::Result<ImportResponse> { async fn import_data(&self, content: &str) -> yaak_commands::Result<ImportResponse> {
Ok(self.pm().import_data(&self.plugin_context(), content).await?) Ok(self.pm().await?.import_data(&self.plugin_context(), content).await?)
} }
async fn reload_plugins(&self, plugins: Vec<Plugin>) -> Vec<(String, String)> { async fn reload_plugins(&self, plugins: Vec<Plugin>) -> Vec<(String, String)> {
self.pm().initialize_all_plugins(plugins, &self.plugin_context()).await match self.pm().await {
Ok(pm) => pm.initialize_all_plugins(plugins, &self.plugin_context()).await,
Err(e) => vec![("*".to_string(), e.to_string())],
}
} }
async fn encrypt_secure_template(&self, template: &str) -> yaak_commands::Result<String> { async fn encrypt_secure_template(&self, template: &str) -> yaak_commands::Result<String> {
let plugin_manager = Arc::new((*self.pm()).clone()); let plugin_manager = Arc::new(self.pm().await?);
let encryption_manager = Arc::new(self.encryption_manager().clone()); let encryption_manager = Arc::new(self.encryption_manager().clone());
Ok(encrypt_secure_template_function( Ok(encrypt_secure_template_function(
plugin_manager, plugin_manager,
@@ -422,7 +434,7 @@ async fn cmd_format_graphql<R: Runtime>(_ctx: ClientCtx<R>, req: CmdFormatGraphq
} }
async fn cmd_http_response_body<R: Runtime>(ctx: ClientCtx<R>, req: CmdHttpResponseBodyReq) -> Result<FilterResponse> { async fn cmd_http_response_body<R: Runtime>(ctx: ClientCtx<R>, req: CmdHttpResponseBodyReq) -> Result<FilterResponse> {
Ok(crate::cmd_http_response_body(ctx.window.clone(), ctx.window.app_handle().state::<PluginManager>(), &req.response_id, req.filter.as_deref()).await?) 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>> {
@@ -441,12 +453,34 @@ async fn cmd_get_http_response_events<R: Runtime>(ctx: ClientCtx<R>, req: CmdGet
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<BatchUpsertResult> { 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).await?) Ok(crate::cmd_import_data(ctx.window.clone(), &req.file_path, req.destination).await?)
} }
async fn cmd_import_url<R: Runtime>(ctx: ClientCtx<R>, req: CmdImportUrlReq) -> Result<BatchUpsertResult> { async fn cmd_import_url<R: Runtime>(ctx: ClientCtx<R>, req: CmdImportUrlReq) -> Result<ImportPlan> {
Ok(crate::cmd_import_url(ctx.window.clone(), &req.url).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> {
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>> {
use crate::models_ext::QueryManagerExt;
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>> {
use crate::models_ext::QueryManagerExt;
let origin = match (req.file_path, req.url) {
(Some(file_path), _) => crate::import::file_origin(&file_path).origin,
(None, Some(url)) => match crate::import::normalize_import_url(&url) {
Ok(url) => crate::import::url_origin(&url).origin,
Err(_) => return Ok(Vec::new()),
},
(None, None) => return Ok(Vec::new()),
};
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>> {
@@ -813,7 +847,7 @@ async fn cmd_ws_close<R: Runtime>(ctx: ClientCtx<R>, req: CmdWsCloseReq) -> Resu
} }
async fn cmd_ws_connect<R: Runtime>(ctx: ClientCtx<R>, req: CmdWsConnectReq) -> Result<WebsocketConnection> { async fn cmd_ws_connect<R: Runtime>(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::<PluginManager>(), ctx.window.app_handle().state::<Mutex<WebsocketManager>>()).await?) 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> {
@@ -843,4 +877,3 @@ async fn cmd_plugins_updates<R: Runtime>(ctx: ClientCtx<R>, _req: CmdPluginsUpda
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?)
} }
+4 -3
View File
@@ -26,9 +26,10 @@ pub(crate) async fn cmd_sync_calculate<R: Runtime>(
return Err(InvalidSyncDirectory(sync_dir.to_string_lossy().to_string()).into()); return Err(InvalidSyncDirectory(sync_dir.to_string_lossy().to_string()).into());
} }
let db = app_handle.db();
let version = app_handle.package_info().version.to_string(); let version = app_handle.package_info().version.to_string();
let db_candidates = get_db_candidates(&db, &version, workspace_id, sync_dir)?; // Scoped so the pooled connection is back before the directory walk below, which is
// as slow as the sync directory is large.
let db_candidates = get_db_candidates(&app_handle.db()?, &version, workspace_id, sync_dir)?;
let fs_candidates = get_fs_candidates(sync_dir)? let fs_candidates = get_fs_candidates(sync_dir)?
.into_iter() .into_iter()
// Only keep items in the same workspace // Only keep items in the same workspace
@@ -49,7 +50,7 @@ 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(); let db = app_handle.db()?;
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)?; let sync_state_ops = apply_sync_ops(&db, &blobs, workspace_id, sync_dir, sync_ops)?;
apply_sync_state_ops(&db, workspace_id, sync_dir, sync_state_ops)?; apply_sync_state_ops(&db, workspace_id, sync_dir, sync_state_ops)?;
+4 -4
View File
@@ -14,7 +14,6 @@ use tokio::task::block_in_place;
use tokio::time::sleep; use tokio::time::sleep;
use ts_rs::TS; use ts_rs::TS;
use yaak_models::util::generate_id; use yaak_models::util::generate_id;
use yaak_plugins::manager::PluginManager;
use url::Url; use url::Url;
use yaak_api::get_system_proxy_url; use yaak_api::get_system_proxy_url;
@@ -76,7 +75,7 @@ impl YaakUpdater {
auto_download: bool, auto_download: bool,
update_trigger: UpdateTrigger, update_trigger: UpdateTrigger,
) -> Result<bool> { ) -> Result<bool> {
let settings = window.db().get_settings(); let settings = window.db()?.get_settings();
let update_key = format!("{:x}", md5::compute(settings.id)); let update_key = format!("{:x}", md5::compute(settings.id));
self.last_check = Some(Instant::now()); self.last_check = Some(Instant::now());
@@ -98,8 +97,9 @@ impl YaakUpdater {
block_in_place(|| { block_in_place(|| {
tauri::async_runtime::block_on(async move { tauri::async_runtime::block_on(async move {
info!("Shutting down plugin manager before update"); info!("Shutting down plugin manager before update");
let plugin_manager = w.state::<PluginManager>(); if let Ok(plugin_manager) = crate::plugins_ext::plugin_manager(&w).await {
plugin_manager.terminate().await; plugin_manager.terminate().await;
}
}); });
}); });
}) })
@@ -1,6 +1,6 @@
use crate::PluginContextExt; use crate::PluginContextExt;
use crate::error::Result; use crate::error::Result;
use crate::import::import_data; use crate::import::{file_origin, import_data, url_origin};
use crate::models_ext::QueryManagerExt; use crate::models_ext::QueryManagerExt;
use log::{info, warn}; use log::{info, warn};
use std::collections::HashMap; use std::collections::HashMap;
@@ -12,7 +12,6 @@ use yaak_api::{ApiClientKind, yaak_api_client};
use yaak_models::util::generate_id; use yaak_models::util::generate_id;
use yaak_plugins::events::{Color, ShowToastRequest}; use yaak_plugins::events::{Color, ShowToastRequest};
use yaak_plugins::install::download_and_install; use yaak_plugins::install::download_and_install;
use yaak_plugins::manager::PluginManager;
pub(crate) async fn handle_deep_link<R: Runtime>( pub(crate) async fn handle_deep_link<R: Runtime>(
app_handle: &AppHandle<R>, app_handle: &AppHandle<R>,
@@ -44,7 +43,7 @@ pub(crate) async fn handle_deep_link<R: Runtime>(
return Ok(()); return Ok(());
} }
let plugin_manager = Arc::new((*window.state::<PluginManager>()).clone()); let plugin_manager = Arc::new(crate::plugins_ext::plugin_manager(window).await?);
let query_manager = app_handle.db_manager(); let query_manager = app_handle.db_manager();
let app_version = app_handle.package_info().version.to_string(); let app_version = app_handle.package_info().version.to_string();
let http_client = yaak_api_client(ApiClientKind::App, &app_version)?; let http_client = yaak_api_client(ApiClientKind::App, &app_version)?;
@@ -70,6 +69,7 @@ pub(crate) async fn handle_deep_link<R: Runtime>(
} }
"import-data" => { "import-data" => {
let mut file_path = query_map.get("path").map(|s| s.to_owned()); let mut file_path = query_map.get("path").map(|s| s.to_owned());
let mut origin = None;
let name = query_map.get("name").map(|s| s.to_owned()).unwrap_or("data".to_string()); let name = query_map.get("name").map(|s| s.to_owned()).unwrap_or("data".to_string());
_ = window.set_focus(); _ = window.set_focus();
@@ -99,6 +99,7 @@ pub(crate) async fn handle_deep_link<R: Runtime>(
.to_string(); .to_string();
fs::write(&p, json)?; fs::write(&p, json)?;
file_path = Some(p); file_path = Some(p);
origin = Some(url_origin(file_url));
} }
let file_path = match file_path { let file_path = match file_path {
@@ -117,7 +118,8 @@ pub(crate) async fn handle_deep_link<R: Runtime>(
} }
}; };
let results = import_data(window, &file_path).await?; let origin = origin.unwrap_or_else(|| file_origin(&file_path));
let results = import_data(window, &file_path, Some(origin)).await?;
window.emit( window.emit(
"show_toast", "show_toast",
ShowToastRequest { ShowToastRequest {
+40 -36
View File
@@ -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;
@@ -22,12 +23,10 @@ use yaak_models::models::{
}; };
use yaak_models::util::UpdateSource; use yaak_models::util::UpdateSource;
use yaak_plugins::events::{CallHttpAuthenticationRequest, HttpHeader, RenderPurpose}; use yaak_plugins::events::{CallHttpAuthenticationRequest, HttpHeader, RenderPurpose};
use yaak_plugins::manager::PluginManager;
use yaak_plugins::template_callback::PluginTemplateCallback; 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>(
@@ -37,14 +36,14 @@ pub async fn cmd_ws_send<R: Runtime>(
window: WebviewWindow<R>, window: WebviewWindow<R>,
ws_manager: State<'_, Mutex<WebsocketManager>>, ws_manager: State<'_, Mutex<WebsocketManager>>,
) -> Result<WebsocketConnection> { ) -> Result<WebsocketConnection> {
let connection = app_handle.db().get_websocket_connection(connection_id)?; let connection = app_handle.db()?.get_websocket_connection(connection_id)?;
match send_websocket_message(&connection, environment_id, &app_handle, &window, &ws_manager) match send_websocket_message(&connection, environment_id, &app_handle, &window, &ws_manager)
.await .await
{ {
Ok(connection) => Ok(connection), Ok(connection) => Ok(connection),
Err(e) => { Err(e) => {
app_handle.db().upsert_websocket_event( app_handle.db()?.upsert_websocket_event(
&WebsocketEvent { &WebsocketEvent {
connection_id: connection.id.clone(), connection_id: connection.id.clone(),
request_id: connection.request_id.clone(), request_id: connection.request_id.clone(),
@@ -69,15 +68,15 @@ async fn send_websocket_message<R: Runtime>(
window: &WebviewWindow<R>, window: &WebviewWindow<R>,
ws_manager: &Mutex<WebsocketManager>, ws_manager: &Mutex<WebsocketManager>,
) -> Result<WebsocketConnection> { ) -> Result<WebsocketConnection> {
let unrendered_request = app_handle.db().get_websocket_request(&connection.request_id)?; let unrendered_request = app_handle.db()?.get_websocket_request(&connection.request_id)?;
let environment_chain = app_handle.db().resolve_environments( let environment_chain = app_handle.db()?.resolve_environments(
&unrendered_request.workspace_id, &unrendered_request.workspace_id,
unrendered_request.folder_id.as_deref(), unrendered_request.folder_id.as_deref(),
environment_id, environment_id,
)?; )?;
let (resolved_request, _auth_context_id) = let (resolved_request, _auth_context_id) =
resolve_websocket_request(&window.db(), &unrendered_request)?; resolve_websocket_request(&window.db()?, &unrendered_request)?;
let plugin_manager = Arc::new((*app_handle.state::<PluginManager>()).clone()); let plugin_manager = Arc::new(crate::plugins_ext::plugin_manager(app_handle).await?);
let encryption_manager = Arc::new((*app_handle.state::<EncryptionManager>()).clone()); let encryption_manager = Arc::new((*app_handle.state::<EncryptionManager>()).clone());
let request = render_websocket_request( let request = render_websocket_request(
&resolved_request, &resolved_request,
@@ -97,7 +96,7 @@ 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.db()?.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(),
@@ -120,7 +119,7 @@ pub async fn cmd_ws_close<R: Runtime>(
ws_manager: State<'_, Mutex<WebsocketManager>>, ws_manager: State<'_, Mutex<WebsocketManager>>,
) -> Result<WebsocketConnection> { ) -> Result<WebsocketConnection> {
let connection = { let connection = {
let db = app_handle.db(); let db = app_handle.db()?;
let connection = db.get_websocket_connection(connection_id)?; let connection = db.get_websocket_connection(connection_id)?;
db.upsert_websocket_connection( db.upsert_websocket_connection(
&WebsocketConnection { state: WebsocketConnectionState::Closing, ..connection }, &WebsocketConnection { state: WebsocketConnectionState::Closing, ..connection },
@@ -142,21 +141,20 @@ pub async fn cmd_ws_connect<R: Runtime>(
cookie_jar_id: Option<&str>, cookie_jar_id: Option<&str>,
app_handle: AppHandle<R>, app_handle: AppHandle<R>,
window: WebviewWindow<R>, window: WebviewWindow<R>,
_plugin_manager: State<'_, PluginManager>,
ws_manager: State<'_, Mutex<WebsocketManager>>, ws_manager: State<'_, Mutex<WebsocketManager>>,
) -> Result<WebsocketConnection> { ) -> Result<WebsocketConnection> {
let unrendered_request = app_handle.db().get_websocket_request(request_id)?; let unrendered_request = app_handle.db()?.get_websocket_request(request_id)?;
let environment_chain = app_handle.db().resolve_environments( let environment_chain = app_handle.db()?.resolve_environments(
&unrendered_request.workspace_id, &unrendered_request.workspace_id,
unrendered_request.folder_id.as_deref(), unrendered_request.folder_id.as_deref(),
environment_id, environment_id,
)?; )?;
let resolved_settings = let resolved_settings =
app_handle.db().resolve_settings_for_websocket_request(&unrendered_request)?; app_handle.db()?.resolve_settings_for_websocket_request(&unrendered_request)?;
let settings = app_handle.db().get_settings(); let settings = app_handle.db()?.get_settings();
let (resolved_request, auth_context_id) = let (resolved_request, auth_context_id) =
resolve_websocket_request(&window.db(), &unrendered_request)?; resolve_websocket_request(&window.db()?, &unrendered_request)?;
let plugin_manager = Arc::new((*app_handle.state::<PluginManager>()).clone()); let plugin_manager = Arc::new(crate::plugins_ext::plugin_manager(&app_handle).await?);
let encryption_manager = Arc::new((*app_handle.state::<EncryptionManager>()).clone()); let encryption_manager = Arc::new((*app_handle.state::<EncryptionManager>()).clone());
let request = render_websocket_request( let request = render_websocket_request(
&resolved_request, &resolved_request,
@@ -171,7 +169,7 @@ pub async fn cmd_ws_connect<R: Runtime>(
) )
.await?; .await?;
let connection = app_handle.db().upsert_websocket_connection( let connection = app_handle.db()?.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(),
@@ -189,7 +187,7 @@ 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.db()?.upsert_websocket_connection(
&WebsocketConnection { &WebsocketConnection {
error: Some(format!("Failed to parse URL {}", e.to_string())), error: Some(format!("Failed to parse URL {}", e.to_string())),
state: WebsocketConnectionState::Closed, state: WebsocketConnectionState::Closed,
@@ -270,7 +268,7 @@ pub async fn cmd_ws_connect<R: Runtime>(
resolved_settings.send_cookies.value || resolved_settings.store_cookies.value, resolved_settings.send_cookies.value || resolved_settings.store_cookies.value,
cookie_jar_id, cookie_jar_id,
) { ) {
(true, Some(id)) => Some(app_handle.db().get_cookie_jar(id)?), (true, Some(id)) => Some(app_handle.db()?.get_cookie_jar(id)?),
_ => None, _ => None,
}; };
let cookie_store = let cookie_store =
@@ -323,7 +321,7 @@ 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.db()?.upsert_websocket_connection(
&WebsocketConnection { &WebsocketConnection {
error: Some(e.to_string()), error: Some(e.to_string()),
state: WebsocketConnectionState::Closed, state: WebsocketConnectionState::Closed,
@@ -334,7 +332,7 @@ pub async fn cmd_ws_connect<R: Runtime>(
} }
}; };
app_handle.db().upsert_websocket_event( app_handle.db()?.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(),
@@ -368,11 +366,11 @@ 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.db()?.upsert_cookie_jar(cookie_jar, &UpdateSource::Background)?;
} }
} }
let connection = app_handle.db().upsert_websocket_connection( let connection = app_handle.db()?.upsert_websocket_connection(
&WebsocketConnection { &WebsocketConnection {
state: WebsocketConnectionState::Connected, state: WebsocketConnectionState::Connected,
headers: response_headers, headers: response_headers,
@@ -396,9 +394,8 @@ pub async fn cmd_ws_connect<R: Runtime>(
has_written_close = true; has_written_close = true;
} }
app_handle let event = || {
.db() app_handle.db()?.upsert_websocket_event(
.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(),
@@ -418,13 +415,15 @@ pub async fn cmd_ws_connect<R: Runtime>(
}, },
&UpdateSource::from_window_label(&window_label), &UpdateSource::from_window_label(&window_label),
) )
.unwrap(); };
if let Err(e) = event() {
warn!("Failed to store WebSocket event: {e}");
}
} }
info!("Websocket connection closed"); info!("Websocket connection closed");
if !has_written_close { if !has_written_close {
app_handle let close_event = app_handle.db().and_then(|db| {
.db() db.upsert_websocket_event(
.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(),
@@ -435,11 +434,13 @@ pub async fn cmd_ws_connect<R: Runtime>(
}, },
&UpdateSource::from_window_label(&window_label), &UpdateSource::from_window_label(&window_label),
) )
.unwrap(); });
if let Err(e) = close_event {
warn!("Failed to store WebSocket close event: {e}");
}
} }
app_handle let closed = app_handle.db().and_then(|db| {
.db() db.upsert_websocket_connection(
.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(),
@@ -448,7 +449,10 @@ pub async fn cmd_ws_connect<R: Runtime>(
}, },
&UpdateSource::from_window_label(&window_label), &UpdateSource::from_window_label(&window_label),
) )
.unwrap(); });
if let Err(e) = closed {
warn!("Failed to mark WebSocket connection closed: {e}");
}
}); });
} }
+9 -6
View File
@@ -16,11 +16,11 @@ use yaak_models::util::UpdateSource;
/// Extension trait for accessing the QueryManager from Tauri Manager types. /// Extension trait for accessing the QueryManager from Tauri Manager types.
/// 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) -> yaak_models::error::Result<ClientDb<'a>>;
} }
impl<'a, R: Runtime, M: Manager<R>> QueryManagerExt<'a, R> for M { impl<'a, R: Runtime, M: Manager<R>> QueryManagerExt<'a, R> for M {
fn db(&'a self) -> ClientDb<'a> { fn db(&'a self) -> yaak_models::error::Result<ClientDb<'a>> {
let qm = self.state::<QueryManager>(); let qm = self.state::<QueryManager>();
qm.inner().connect() qm.inner().connect()
} }
@@ -137,7 +137,7 @@ 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( window.app_handle().db()?.set_key_value_str(
KV_ACTIVATION_ID_KEY, KV_ACTIVATION_ID_KEY,
KV_NAMESPACE, KV_NAMESPACE,
body.activation_id.as_str(), body.activation_id.as_str(),
@@ -172,7 +172,7 @@ 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.db()?.delete_key_value(
KV_ACTIVATION_ID_KEY, KV_ACTIVATION_ID_KEY,
KV_NAMESPACE, KV_NAMESPACE,
&UpdateSource::from_window_label(window.label()), &UpdateSource::from_window_label(window.label()),
@@ -191,7 +191,7 @@ pub async fn check_license<R: Runtime>(window: &WebviewWindow<R>) -> Result<Lice
CheckActivationRequestPayload { app_platform: get_os_str().to_string(), app_version }; CheckActivationRequestPayload { app_platform: get_os_str().to_string(), app_version };
let activation_id = get_activation_id(window.app_handle()).await; let activation_id = get_activation_id(window.app_handle()).await;
let settings = window.db().get_settings(); let settings = window.db()?.get_settings();
let trial_end = settings.created_at.add(Duration::from_secs(TRIAL_SECONDS)).and_utc(); let trial_end = settings.created_at.add(Duration::from_secs(TRIAL_SECONDS)).and_utc();
let has_activation_id = !activation_id.is_empty(); let has_activation_id = !activation_id.is_empty();
@@ -238,5 +238,8 @@ fn build_url(path: &str) -> String {
} }
pub async fn get_activation_id<R: Runtime>(app_handle: &AppHandle<R>) -> String { pub async fn get_activation_id<R: Runtime>(app_handle: &AppHandle<R>) -> String {
app_handle.db().get_key_value_str(KV_ACTIVATION_ID_KEY, KV_NAMESPACE, "") app_handle
.db()
.map(|db| db.get_key_value_str(KV_ACTIVATION_ID_KEY, KV_NAMESPACE, ""))
.unwrap_or_default()
} }
+1 -1
View File
@@ -12,7 +12,7 @@ pub use connection_or_tx::ConnectionOrTx;
pub use db_context::DbContext; pub use db_context::DbContext;
pub use error::{Error, Result}; pub use error::{Error, Result};
pub use migrate::run_migrations; pub use migrate::run_migrations;
pub use pool::{PoolError, SqliteConn, SqlitePool}; pub use pool::{PoolError, PoolStatus, SqliteConn, SqlitePool, status as pool_status};
pub use traits::{UpsertModelInfo, upsert_date}; pub use traits::{UpsertModelInfo, upsert_date};
pub use update_source::{ModelChangeEvent, UpdateSource}; pub use update_source::{ModelChangeEvent, UpdateSource};
pub use util::{generate_id, generate_id_of_length, generate_prefixed_id}; pub use util::{generate_id, generate_id_of_length, generate_prefixed_id};
+27
View File
@@ -23,17 +23,39 @@
//! 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). //! connection blocks on `busy_timeout` and then fails).
/// What a pool looks like from outside at one moment. Enough to tell "everything is
/// checked out" apart from "nothing could be opened", which are unrelated problems that
/// both surface as an acquire timeout.
#[derive(Debug, Clone, Copy)]
pub struct PoolStatus {
pub connections: u32,
pub idle: u32,
}
impl std::fmt::Display for PoolStatus {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{} open, {} idle", self.connections, self.idle)
}
}
#[cfg(not(target_arch = "wasm32"))] #[cfg(not(target_arch = "wasm32"))]
mod imp { mod imp {
use super::PoolStatus;
use r2d2_sqlite::SqliteConnectionManager; use r2d2_sqlite::SqliteConnectionManager;
pub type SqlitePool = r2d2::Pool<SqliteConnectionManager>; pub type SqlitePool = r2d2::Pool<SqliteConnectionManager>;
pub type SqliteConn = r2d2::PooledConnection<SqliteConnectionManager>; pub type SqliteConn = r2d2::PooledConnection<SqliteConnectionManager>;
pub type PoolError = r2d2::Error; pub type PoolError = r2d2::Error;
pub fn status(pool: &SqlitePool) -> PoolStatus {
let state = pool.state();
PoolStatus { connections: state.connections, idle: state.idle_connections }
}
} }
#[cfg(target_arch = "wasm32")] #[cfg(target_arch = "wasm32")]
mod imp { mod imp {
use super::PoolStatus;
use rusqlite::Connection; use rusqlite::Connection;
use std::ops::Deref; use std::ops::Deref;
use std::rc::Rc; use std::rc::Rc;
@@ -66,6 +88,11 @@ mod imp {
#[derive(Debug, thiserror::Error)] #[derive(Debug, thiserror::Error)]
pub enum PoolError {} pub enum PoolError {}
/// The one connection, which is never checked out and never unavailable.
pub fn status(_pool: &SqlitePool) -> PoolStatus {
PoolStatus { connections: 1, idle: 1 }
}
#[derive(Debug)] #[derive(Debug)]
pub struct SqliteConn(Rc<Connection>); pub struct SqliteConn(Rc<Connection>);
+13
View File
@@ -11,6 +11,7 @@ export type AnyModel =
| HttpRequest | HttpRequest
| HttpResponse | HttpResponse
| HttpResponseEvent | HttpResponseEvent
| ImportSource
| KeyValue | KeyValue
| Plugin | Plugin
| Settings | Settings
@@ -318,6 +319,18 @@ export type HttpUrlParameter = {
export type HttpVersion = "auto" | "http1" | "http2"; export type HttpVersion = "auto" | "http1" | "http2";
export type ImportSource = {
model: "import_source";
id: string;
createdAt: string;
updatedAt: string;
workspaceId: string;
importer: string;
origin: string;
originLabel: string;
lastImportedAt: 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 };
+11 -5
View File
@@ -3,10 +3,10 @@ import type { PluginNameVersion, PluginSearchResponse, PluginUpdatesResponse } f
import type { CallFolderActionRequest, CallGrpcRequestActionRequest, CallHttpRequestActionRequest, CallWebsocketRequestActionRequest, CallWorkspaceActionRequest, FilterResponse, GetFolderActionsResponse, GetGrpcRequestActionsResponse, GetHttpAuthenticationConfigResponse, GetHttpAuthenticationSummaryResponse, GetHttpRequestActionsResponse, GetTemplateFunctionConfigResponse, GetTemplateFunctionSummaryResponse, GetThemesResponse, GetWebsocketRequestActionsResponse, GetWorkspaceActionsResponse, JsonPrimitive, RenderPurpose } from "./gen_events"; import type { CallFolderActionRequest, CallGrpcRequestActionRequest, CallHttpRequestActionRequest, CallWebsocketRequestActionRequest, CallWorkspaceActionRequest, FilterResponse, GetFolderActionsResponse, GetGrpcRequestActionsResponse, GetHttpAuthenticationConfigResponse, GetHttpAuthenticationSummaryResponse, GetHttpRequestActionsResponse, GetTemplateFunctionConfigResponse, GetTemplateFunctionSummaryResponse, GetThemesResponse, GetWebsocketRequestActionsResponse, GetWorkspaceActionsResponse, JsonPrimitive, RenderPurpose } from "./gen_events";
import type { BranchDeleteResult, CloneResult, GitBranchInfo, GitCommit, GitFileDiff, GitRemote, GitStatusSummary, GitWorktreeStatus, PullResult, PushResult } from "./gen_git"; import type { BranchDeleteResult, CloneResult, GitBranchInfo, GitCommit, GitFileDiff, GitRemote, GitStatusSummary, GitWorktreeStatus, PullResult, PushResult } from "./gen_git";
import type { ServiceDefinition } from "./gen_grpc"; import type { ServiceDefinition } from "./gen_grpc";
import type { AnyModel, GraphQlIntrospection, GrpcEvent, HttpRequest, HttpRequestHeader, HttpResponse, HttpResponseEvent, Plugin, Settings, WebsocketConnection, WebsocketEvent, WorkspaceMeta } from "./gen_models"; import type { AnyModel, GraphQlIntrospection, GrpcEvent, HttpRequest, HttpRequestHeader, HttpResponse, HttpResponseEvent, ImportSource, Plugin, Settings, WebsocketConnection, WebsocketEvent, WorkspaceMeta } from "./gen_models";
import type { PluginMetadata } from "./gen_search"; import type { PluginMetadata } from "./gen_search";
import type { SyncOp } from "./gen_sync"; import type { SyncOp } from "./gen_sync";
import type { BatchUpsertResult } from "./gen_util"; import type { BatchUpsertResult, ImportDestination, ImportPlan } from "./gen_util";
import type { Tokens } from "./parser"; import type { Tokens } from "./parser";
import type { ServerSentEvent } from "./sse"; import type { ServerSentEvent } from "./sse";
@@ -29,6 +29,8 @@ export type CmdCallWorkspaceActionReq = { req: CallWorkspaceActionRequest, };
export type CmdCheckForUpdatesReq = Record<string, never>; export type CmdCheckForUpdatesReq = Record<string, never>;
export type CmdCommitImportReq = { plan: ImportPlan, };
export type CmdCurlToRequestReq = { command: string, workspaceId: string, }; export type CmdCurlToRequestReq = { command: string, workspaceId: string, };
export type CmdDecryptTemplateReq = { template: string, }; export type CmdDecryptTemplateReq = { template: string, };
@@ -141,9 +143,13 @@ export type CmdHttpResponseBodyPathReq = { responseId: string, };
export type CmdHttpResponseBodyReq = { responseId: string, filter: string | null, }; export type CmdHttpResponseBodyReq = { responseId: string, filter: string | null, };
export type CmdImportDataReq = { filePath: string, }; export type CmdImportDataReq = { filePath: string, destination: ImportDestination, };
export type CmdImportUrlReq = { url: string, }; export type CmdImportSourcesForOriginReq = { filePath?: string, url?: string, };
export type CmdImportUrlReq = { url: string, destination: ImportDestination, };
export type CmdListImportSourcesReq = { workspaceId: string, };
export type CmdMetadataReq = Record<string, never>; export type CmdMetadataReq = Record<string, never>;
@@ -248,6 +254,6 @@ export type ModelsWebsocketEventsReq = { connectionId: string, };
export type ModelsWorkspaceModelsReq = { workspaceId: string | null, }; export type ModelsWorkspaceModelsReq = { workspaceId: string | null, };
export type RpcSchema = { cmd_metadata: [CmdMetadataReq, AppMetaData], cmd_template_tokens_to_string: [CmdTemplateTokensToStringReq, string], cmd_render_template: [CmdRenderTemplateReq, string], cmd_send_feedback: [CmdSendFeedbackReq, null], cmd_dismiss_notification: [CmdDismissNotificationReq, null], cmd_grpc_reflect: [CmdGrpcReflectReq, Array<ServiceDefinition>], cmd_grpc_go: [CmdGrpcGoReq, string], cmd_restart: [CmdRestartReq, null], cmd_send_ephemeral_request: [CmdSendEphemeralRequestReq, EphemeralHttpResponse], cmd_format_json: [CmdFormatJsonReq, string], cmd_format_graphql: [CmdFormatGraphqlReq, string], cmd_http_response_body: [CmdHttpResponseBodyReq, FilterResponse], cmd_http_response_body_path: [CmdHttpResponseBodyPathReq, string | null], cmd_http_request_body: [CmdHttpRequestBodyReq, Array<number> | null], cmd_get_sse_events: [CmdGetSseEventsReq, Array<ServerSentEvent>], cmd_get_http_response_events: [CmdGetHttpResponseEventsReq, Array<HttpResponseEvent>], cmd_import_data: [CmdImportDataReq, BatchUpsertResult], cmd_import_url: [CmdImportUrlReq, BatchUpsertResult], cmd_http_request_actions: [CmdHttpRequestActionsReq, Array<GetHttpRequestActionsResponse>], cmd_websocket_request_actions: [CmdWebsocketRequestActionsReq, Array<GetWebsocketRequestActionsResponse>], cmd_call_websocket_request_action: [CmdCallWebsocketRequestActionReq, null], cmd_workspace_actions: [CmdWorkspaceActionsReq, Array<GetWorkspaceActionsResponse>], cmd_call_workspace_action: [CmdCallWorkspaceActionReq, null], cmd_folder_actions: [CmdFolderActionsReq, Array<GetFolderActionsResponse>], cmd_call_folder_action: [CmdCallFolderActionReq, null], cmd_grpc_request_actions: [CmdGrpcRequestActionsReq, Array<GetGrpcRequestActionsResponse>], cmd_template_function_summaries: [CmdTemplateFunctionSummariesReq, Array<GetTemplateFunctionSummaryResponse>], cmd_template_function_config: [CmdTemplateFunctionConfigReq, GetTemplateFunctionConfigResponse], cmd_get_http_authentication_summaries: [CmdGetHttpAuthenticationSummariesReq, Array<GetHttpAuthenticationSummaryResponse>], cmd_get_http_authentication_config: [CmdGetHttpAuthenticationConfigReq, GetHttpAuthenticationConfigResponse], cmd_call_http_request_action: [CmdCallHttpRequestActionReq, null], cmd_call_grpc_request_action: [CmdCallGrpcRequestActionReq, null], cmd_call_http_authentication_action: [CmdCallHttpAuthenticationActionReq, null], cmd_curl_to_request: [CmdCurlToRequestReq, HttpRequest], cmd_export_data: [CmdExportDataReq, null], cmd_save_base64_to_binary: [CmdSaveBase64ToBinaryReq, null], cmd_save_response: [CmdSaveResponseReq, null], cmd_send_http_request: [CmdSendHttpRequestReq, HttpResponse], cmd_reload_plugins: [CmdReloadPluginsReq, Array<[string, string]>], cmd_plugin_info: [CmdPluginInfoReq, PluginMetadata], cmd_delete_all_grpc_connections: [CmdDeleteAllGrpcConnectionsReq, null], cmd_delete_send_history: [CmdDeleteSendHistoryReq, null], cmd_delete_all_http_responses: [CmdDeleteAllHttpResponsesReq, null], cmd_get_workspace_meta: [CmdGetWorkspaceMetaReq, WorkspaceMeta], cmd_new_child_window: [CmdNewChildWindowReq, null], cmd_new_main_window: [CmdNewMainWindowReq, null], cmd_check_for_updates: [CmdCheckForUpdatesReq, boolean], cmd_decrypt_template: [CmdDecryptTemplateReq, string], cmd_secure_template: [CmdSecureTemplateReq, string], cmd_get_themes: [CmdGetThemesReq, Array<GetThemesResponse>], cmd_enable_encryption: [CmdEnableEncryptionReq, null], cmd_reveal_workspace_key: [CmdRevealWorkspaceKeyReq, string], cmd_set_workspace_key: [CmdSetWorkspaceKeyReq, null], cmd_disable_encryption: [CmdDisableEncryptionReq, null], cmd_default_headers: [CmdDefaultHeadersReq, Array<HttpRequestHeader>], models_upsert: [ModelsUpsertReq, string], models_delete: [ModelsDeleteReq, string], models_duplicate: [ModelsDuplicateReq, string], models_websocket_events: [ModelsWebsocketEventsReq, Array<WebsocketEvent>], models_grpc_events: [ModelsGrpcEventsReq, Array<GrpcEvent>], models_get_settings: [ModelsGetSettingsReq, Settings], models_get_graphql_introspection: [ModelsGetGraphqlIntrospectionReq, GraphQlIntrospection | null], models_upsert_graphql_introspection: [ModelsUpsertGraphqlIntrospectionReq, GraphQlIntrospection], models_workspace_models: [ModelsWorkspaceModelsReq, string], cmd_git_checkout: [CmdGitCheckoutReq, string], cmd_git_branch: [CmdGitBranchReq, null], cmd_git_delete_branch: [CmdGitDeleteBranchReq, BranchDeleteResult], cmd_git_delete_remote_branch: [CmdGitDeleteRemoteBranchReq, null], cmd_git_merge_branch: [CmdGitMergeBranchReq, null], cmd_git_rename_branch: [CmdGitRenameBranchReq, null], cmd_git_status: [CmdGitStatusReq, GitStatusSummary], cmd_git_branch_info: [CmdGitBranchInfoReq, GitBranchInfo], cmd_git_worktree_status: [CmdGitWorktreeStatusReq, GitWorktreeStatus], cmd_git_log: [CmdGitLogReq, Array<GitCommit>], cmd_git_log_for_file: [CmdGitLogForFileReq, Array<GitCommit>], cmd_git_file_diff_for_commit: [CmdGitFileDiffForCommitReq, GitFileDiff], cmd_git_initialize: [CmdGitInitializeReq, nuLine truncated export type RpcSchema = { cmd_metadata: [CmdMetadataReq, AppMetaData], cmd_template_tokens_to_string: [CmdTemplateTokensToStringReq, string], cmd_render_template: [CmdRenderTemplateReq, string], cmd_send_feedback: [CmdSendFeedbackReq, null], cmd_dismiss_notification: [CmdDismissNotificationReq, null], cmd_grpc_reflect: [CmdGrpcReflectReq, Array<ServiceDefinition>], cmd_grpc_go: [CmdGrpcGoReq, string], cmd_restart: [CmdRestartReq, null], cmd_send_ephemeral_request: [CmdSendEphemeralRequestReq, EphemeralHttpResponse], cmd_format_json: [CmdFormatJsonReq, string], cmd_format_graphql: [CmdFormatGraphqlReq, string], cmd_http_response_body: [CmdHttpResponseBodyReq, FilterResponse], cmd_http_response_body_path: [CmdHttpResponseBodyPathReq, string | null], cmd_http_request_body: [CmdHttpRequestBodyReq, Array<number> | null], cmd_get_sse_events: [CmdGetSseEventsReq, Array<ServerSentEvent>], cmd_get_http_response_events: [CmdGetHttpResponseEventsReq, Array<HttpResponseEvent>], cmd_import_data: [CmdImportDataReq, ImportPlan], cmd_import_url: [CmdImportUrlReq, ImportPlan], cmd_commit_import: [CmdCommitImportReq, BatchUpsertResult], cmd_list_import_sources: [CmdListImportSourcesReq, Array<ImportSource>], cmd_import_sources_for_origin: [CmdImportSourcesForOriginReq, Array<ImportSource>], cmd_http_request_actions: [CmdHttpRequestActionsReq, Array<GetHttpRequestActionsResponse>], cmd_websocket_request_actions: [CmdWebsocketRequestActionsReq, Array<GetWebsocketRequestActionsResponse>], cmd_call_websocket_request_action: [CmdCallWebsocketRequestActionReq, null], cmd_workspace_actions: [CmdWorkspaceActionsReq, Array<GetWorkspaceActionsResponse>], cmd_call_workspace_action: [CmdCallWorkspaceActionReq, null], cmd_folder_actions: [CmdFolderActionsReq, Array<GetFolderActionsResponse>], cmd_call_folder_action: [CmdCallFolderActionReq, null], cmd_grpc_request_actions: [CmdGrpcRequestActionsReq, Array<GetGrpcRequestActionsResponse>], cmd_template_function_summaries: [CmdTemplateFunctionSummariesReq, Array<GetTemplateFunctionSummaryResponse>], cmd_template_function_config: [CmdTemplateFunctionConfigReq, GetTemplateFunctionConfigResponse], cmd_get_http_authentication_summaries: [CmdGetHttpAuthenticationSummariesReq, Array<GetHttpAuthenticationSummaryResponse>], cmd_get_http_authentication_config: [CmdGetHttpAuthenticationConfigReq, GetHttpAuthenticationConfigResponse], cmd_call_http_request_action: [CmdCallHttpRequestActionReq, null], cmd_call_grpc_request_action: [CmdCallGrpcRequestActionReq, null], cmd_call_http_authentication_action: [CmdCallHttpAuthenticationActionReq, null], cmd_curl_to_request: [CmdCurlToRequestReq, HttpRequest], cmd_export_data: [CmdExportDataReq, null], cmd_save_base64_to_binary: [CmdSaveBase64ToBinaryReq, null], cmd_save_response: [CmdSaveResponseReq, null], cmd_send_http_request: [CmdSendHttpRequestReq, HttpResponse], cmd_reload_plugins: [CmdReloadPluginsReq, Array<[string, string]>], cmd_plugin_info: [CmdPluginInfoReq, PluginMetadata], cmd_delete_all_grpc_connections: [CmdDeleteAllGrpcConnectionsReq, null], cmd_delete_send_history: [CmdDeleteSendHistoryReq, null], cmd_delete_all_http_responses: [CmdDeleteAllHttpResponsesReq, null], cmd_get_workspace_meta: [CmdGetWorkspaceMetaReq, WorkspaceMeta], cmd_new_child_window: [CmdNewChildWindowReq, null], cmd_new_main_window: [CmdNewMainWindowReq, null], cmd_check_for_updates: [CmdCheckForUpdatesReq, boolean], cmd_decrypt_template: [CmdDecryptTemplateReq, string], cmd_secure_template: [CmdSecureTemplateReq, string], cmd_get_themes: [CmdGetThemesReq, Array<GetThemesResponse>], cmd_enable_encryption: [CmdEnableEncryptionReq, null], cmd_reveal_workspace_key: [CmdRevealWorkspaceKeyReq, string], cmd_set_workspace_key: [CmdSetWorkspaceKeyReq, null], cmd_disable_encryption: [CmdDisableEncryptionReq, null], cmd_default_headers: [CmdDefaultHeadersReq, Array<HttpRequestHeader>], models_upsert: [ModelsUpsertReq, string], models_delete: [ModelsDeleteReq, string], models_duplicate: [ModelsDuplicateReq, string], models_websocket_events: [ModelsWebsocketEventsReq, Array<WebsocketEvent>], models_grpc_events: [ModelsGrpcEventsReq, Array<GrpcEvent>], models_get_settings: [ModelsGetSettingsReq, Settings], models_get_graphql_introspection: [ModelsGetGraphqlIntrospectionReq, GraphQlIntrospection | null], models_upsert_graphql_introspection: [ModelsUpsertGraphqlIntrospectionReq, GraphQlIntrospection], models_workspace_models: [ModelsWorkspaceModelsReq, string], cmd_git_checkout: [CmdGitCheckoutReq, string], cmd_git_branch: [CmdGitBranchReq, null], cmd_git_delete_branch: [CmdGitDeleteBranchReq, BranchDeleteResult], cmd_git_delete_remote_branch: [CmdGitDeleteRemoteBranchReq, null], cmd_git_merge_branch: [CmdGitMergeBranchReq, null], cmd_git_rename_branch: [CmdGitRenameBranchReq, null], cmd_git_status: [CmdGitStatusReq, GitStatusSummary], cmd_git_branch_info: [CmdGitBranchInfoReq, GitBranchInfo], cmd_git_worktree_status: [CmdGitWorktreeStatusReq, GitWorktreeStatus], cmd_git_log: [CmdGitLogRLine truncated
export type WatchResult = { unlistenEvent: string, }; export type WatchResult = { unlistenEvent: string, };
+105 -2
View File
@@ -1,4 +1,107 @@
// 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";
/**
* Where a staged import will be committed.
*
* The destination workspace and optional folder IDs are captured in the plan so the preview describes
* the exact destination that confirmation will use.
*/
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.
*/
export type ImportOrigin = {
/**
* The absolute file path or URL the contents were read from.
*/
origin: string;
label: string;
};
export type ImportPlan = {
importer: string;
destination: ImportDestination;
resources: BatchUpsertResult;
warnings: Array<ImportPlanWarning>;
/**
* Stable source key for every model in `resources`, keyed by its planned ID.
*/
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"
| "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>;
};
/**
* Extra context for an action that would otherwise be indistinguishable from its plain form.
*/
export type ImportPlanReason = "moved_into_ignored_folder";
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.
*/
export type ImportResourceType =
| "environment"
| "folder"
| "grpc_request"
| "http_request"
| "websocket_request"
| "workspace";
+34 -4
View File
@@ -21,9 +21,10 @@ use yaak_git::{
use yaak_grpc::ServiceDefinition; use yaak_grpc::ServiceDefinition;
use yaak_models::models::{ use yaak_models::models::{
AnyModel, GraphQlIntrospection, GrpcEvent, HttpRequest, HttpRequestHeader, HttpResponse, AnyModel, GraphQlIntrospection, GrpcEvent, HttpRequest, HttpRequestHeader, HttpResponse,
HttpResponseEvent, Plugin, Settings, WebsocketConnection, WebsocketEvent, WorkspaceMeta, HttpResponseEvent, ImportSource, Plugin, Settings, WebsocketConnection, WebsocketEvent,
WorkspaceMeta,
}; };
use yaak_models::util::BatchUpsertResult; use yaak_models::util::{BatchUpsertResult, ImportDestination, ImportPlan};
use yaak_plugins::api::{PluginNameVersion, PluginSearchResponse, PluginUpdatesResponse}; use yaak_plugins::api::{PluginNameVersion, PluginSearchResponse, PluginUpdatesResponse};
use yaak_plugins::events::{ use yaak_plugins::events::{
CallFolderActionRequest, CallGrpcRequestActionRequest, CallHttpRequestActionRequest, CallFolderActionRequest, CallGrpcRequestActionRequest, CallHttpRequestActionRequest,
@@ -229,6 +230,7 @@ pub struct CmdGetHttpResponseEventsReq {
#[ts(export, export_to = "gen_rpc.ts")] #[ts(export, export_to = "gen_rpc.ts")]
pub struct CmdImportDataReq { pub struct CmdImportDataReq {
pub file_path: String, pub file_path: String,
pub destination: ImportDestination,
} }
#[derive(Debug, Deserialize, TS)] #[derive(Debug, Deserialize, TS)]
@@ -236,6 +238,31 @@ pub struct CmdImportDataReq {
#[ts(export, export_to = "gen_rpc.ts")] #[ts(export, export_to = "gen_rpc.ts")]
pub struct CmdImportUrlReq { pub struct CmdImportUrlReq {
pub url: String, pub url: String,
pub destination: ImportDestination,
}
#[derive(Debug, Deserialize, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export, export_to = "gen_rpc.ts")]
pub struct CmdCommitImportReq {
pub plan: ImportPlan,
}
#[derive(Debug, Deserialize, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export, export_to = "gen_rpc.ts")]
pub struct CmdListImportSourcesReq {
pub workspace_id: String,
}
#[derive(Debug, Deserialize, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export, export_to = "gen_rpc.ts")]
pub struct CmdImportSourcesForOriginReq {
#[ts(optional)]
pub file_path: Option<String>,
#[ts(optional)]
pub url: Option<String>,
} }
#[derive(Debug, Deserialize, TS)] #[derive(Debug, Deserialize, TS)]
@@ -909,8 +936,11 @@ macro_rules! with_commands {
cmd_http_request_body(CmdHttpRequestBodyReq) -> Option<Vec<u8>>, cmd_http_request_body(CmdHttpRequestBodyReq) -> Option<Vec<u8>>,
cmd_get_sse_events(CmdGetSseEventsReq) -> Vec<ServerSentEvent>, cmd_get_sse_events(CmdGetSseEventsReq) -> Vec<ServerSentEvent>,
cmd_get_http_response_events(CmdGetHttpResponseEventsReq) -> Vec<HttpResponseEvent>, cmd_get_http_response_events(CmdGetHttpResponseEventsReq) -> Vec<HttpResponseEvent>,
cmd_import_data(CmdImportDataReq) -> BatchUpsertResult, cmd_import_data(CmdImportDataReq) -> ImportPlan,
cmd_import_url(CmdImportUrlReq) -> BatchUpsertResult, cmd_import_url(CmdImportUrlReq) -> ImportPlan,
cmd_commit_import(CmdCommitImportReq) -> BatchUpsertResult,
cmd_list_import_sources(CmdListImportSourcesReq) -> Vec<ImportSource>,
cmd_import_sources_for_origin(CmdImportSourcesForOriginReq) -> Vec<ImportSource>,
cmd_http_request_actions(CmdHttpRequestActionsReq) -> Vec<GetHttpRequestActionsResponse>, cmd_http_request_actions(CmdHttpRequestActionsReq) -> Vec<GetHttpRequestActionsResponse>,
cmd_websocket_request_actions(CmdWebsocketRequestActionsReq) -> Vec<GetWebsocketRequestActionsResponse>, cmd_websocket_request_actions(CmdWebsocketRequestActionsReq) -> Vec<GetWebsocketRequestActionsResponse>,
cmd_call_websocket_request_action(CmdCallWebsocketRequestActionReq) -> (), cmd_call_websocket_request_action(CmdCallWebsocketRequestActionReq) -> (),
+6 -6
View File
@@ -63,7 +63,7 @@ pub async fn cmd_call_http_request_action<H: PluginHost>(
req: CmdCallHttpRequestActionReq, req: CmdCallHttpRequestActionReq,
) -> Result<()> { ) -> Result<()> {
let inner = req.req; let inner = req.req;
let http_request = resolve_http_request(&host.db(), &inner.args.http_request)?.0; let http_request = resolve_http_request(&host.db()?, &inner.args.http_request)?.0;
host.call_http_request_action(CallHttpRequestActionRequest { host.call_http_request_action(CallHttpRequestActionRequest {
args: CallHttpRequestActionArgs { http_request }, args: CallHttpRequestActionArgs { http_request },
..inner ..inner
@@ -76,7 +76,7 @@ pub async fn cmd_call_grpc_request_action<H: PluginHost>(
req: CmdCallGrpcRequestActionReq, req: CmdCallGrpcRequestActionReq,
) -> Result<()> { ) -> Result<()> {
let inner = req.req; let inner = req.req;
let grpc_request = resolve_grpc_request(&host.db(), &inner.args.grpc_request)?.0; let grpc_request = resolve_grpc_request(&host.db()?, &inner.args.grpc_request)?.0;
host.call_grpc_request_action(CallGrpcRequestActionRequest { host.call_grpc_request_action(CallGrpcRequestActionRequest {
args: CallGrpcRequestActionArgs { grpc_request, ..inner.args }, args: CallGrpcRequestActionArgs { grpc_request, ..inner.args },
..inner ..inner
@@ -89,7 +89,7 @@ pub async fn cmd_call_websocket_request_action<H: PluginHost>(
req: CmdCallWebsocketRequestActionReq, req: CmdCallWebsocketRequestActionReq,
) -> Result<()> { ) -> Result<()> {
let inner = req.req; let inner = req.req;
let websocket_request = host.db().get_websocket_request(&inner.args.websocket_request.id)?; let websocket_request = host.db()?.get_websocket_request(&inner.args.websocket_request.id)?;
host.call_websocket_request_action(CallWebsocketRequestActionRequest { host.call_websocket_request_action(CallWebsocketRequestActionRequest {
args: CallWebsocketRequestActionArgs { websocket_request }, args: CallWebsocketRequestActionArgs { websocket_request },
..inner ..inner
@@ -102,7 +102,7 @@ pub async fn cmd_call_workspace_action<H: PluginHost>(
req: CmdCallWorkspaceActionReq, req: CmdCallWorkspaceActionReq,
) -> Result<()> { ) -> Result<()> {
let inner = req.req; let inner = req.req;
let workspace = host.db().get_workspace(&inner.args.workspace.id)?; let workspace = host.db()?.get_workspace(&inner.args.workspace.id)?;
host.call_workspace_action(CallWorkspaceActionRequest { host.call_workspace_action(CallWorkspaceActionRequest {
args: CallWorkspaceActionArgs { workspace }, args: CallWorkspaceActionArgs { workspace },
..inner ..inner
@@ -115,7 +115,7 @@ pub async fn cmd_call_folder_action<H: PluginHost>(
req: CmdCallFolderActionReq, req: CmdCallFolderActionReq,
) -> Result<()> { ) -> Result<()> {
let inner = req.req; let inner = req.req;
let folder = host.db().get_folder(&inner.args.folder.id)?; let folder = host.db()?.get_folder(&inner.args.folder.id)?;
host.call_folder_action(CallFolderActionRequest { host.call_folder_action(CallFolderActionRequest {
args: CallFolderActionArgs { folder }, args: CallFolderActionArgs { folder },
..inner ..inner
@@ -152,6 +152,6 @@ pub async fn cmd_reload_plugins<H: PluginHost>(
host: H, host: H,
_req: CmdReloadPluginsReq, _req: CmdReloadPluginsReq,
) -> Result<Vec<(String, String)>> { ) -> Result<Vec<(String, String)>> {
let plugins = host.db().list_plugins()?; let plugins = host.db()?.list_plugins()?;
Ok(host.reload_plugins(plugins).await) Ok(host.reload_plugins(plugins).await)
} }
+8 -3
View File
@@ -68,11 +68,11 @@ pub trait Host: Clone {
PluginContext::new(Some(self.client_id().to_string()), self.session().workspace_id) PluginContext::new(Some(self.client_id().to_string()), self.session().workspace_id)
} }
fn db(&self) -> ClientDb<'_> { fn db(&self) -> yaak_models::error::Result<ClientDb<'_>> {
self.query_manager().connect() self.query_manager().connect()
} }
fn blobs(&self) -> BlobContext { fn blobs(&self) -> yaak_models::error::Result<BlobContext> {
self.blob_manager().connect() self.blob_manager().connect()
} }
} }
@@ -121,7 +121,12 @@ pub trait PluginHost: Host {
/// a render — the variables come from the environment chain, which is an /// a render — the variables come from the environment chain, which is an
/// ordinary database read — so handing back the callback keeps the rest of /// ordinary database read — so handing back the callback keeps the rest of
/// rendering shared instead of pushing whole commands behind this trait. /// rendering shared instead of pushing whole commands behind this trait.
fn template_callback(&self, purpose: RenderPurpose) -> impl TemplateCallback; /// Async so hosts that finish booting their plugin runtime in the
/// background can wait for it here.
fn template_callback(
&self,
purpose: RenderPurpose,
) -> impl Future<Output = crate::Result<impl TemplateCallback>>;
/// Every template function the installed plugins expose, for the /// Every template function the installed plugins expose, for the
/// autocomplete menu. /// autocomplete menu.
+15 -13
View File
@@ -11,7 +11,7 @@ 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 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(yaak_models::models_ops::upsert_model(&db, blobs, req.model, &source)?)
@@ -49,25 +49,25 @@ pub async fn models_websocket_events<H: Host>(
host: H, host: H,
req: ModelsWebsocketEventsReq, req: ModelsWebsocketEventsReq,
) -> Result<Vec<WebsocketEvent>> { ) -> Result<Vec<WebsocketEvent>> {
Ok(host.db().list_websocket_events(&req.connection_id)?) Ok(host.db()?.list_websocket_events(&req.connection_id)?)
} }
pub async fn models_grpc_events<H: Host>( pub async fn models_grpc_events<H: Host>(
host: H, host: H,
req: ModelsGrpcEventsReq, req: ModelsGrpcEventsReq,
) -> Result<Vec<GrpcEvent>> { ) -> Result<Vec<GrpcEvent>> {
Ok(host.db().list_grpc_events(&req.connection_id)?) Ok(host.db()?.list_grpc_events(&req.connection_id)?)
} }
pub async fn models_get_settings<H: Host>(host: H, _req: ModelsGetSettingsReq) -> Result<Settings> { pub async fn models_get_settings<H: Host>(host: H, _req: ModelsGetSettingsReq) -> Result<Settings> {
Ok(host.db().get_settings()) Ok(host.db()?.get_settings())
} }
pub async fn models_get_graphql_introspection<H: Host>( pub async fn models_get_graphql_introspection<H: Host>(
host: H, host: H,
req: ModelsGetGraphqlIntrospectionReq, req: ModelsGetGraphqlIntrospectionReq,
) -> Result<Option<GraphQlIntrospection>> { ) -> Result<Option<GraphQlIntrospection>> {
Ok(host.db().get_graphql_introspection(&req.request_id)) Ok(host.db()?.get_graphql_introspection(&req.request_id))
} }
pub async fn models_upsert_graphql_introspection<H: Host>( pub async fn models_upsert_graphql_introspection<H: Host>(
@@ -75,7 +75,7 @@ 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.db()?.upsert_graphql_introspection(
&req.workspace_id, &req.workspace_id,
&req.request_id, &req.request_id,
req.content, req.content,
@@ -96,14 +96,14 @@ pub async fn models_workspace_models<H: PluginHost>(
// Add the global models // Add the global models
{ {
let db = host.db(); let db = host.db()?;
l.push(db.get_settings().into()); l.push(db.get_settings().into());
l.append(&mut db.list_workspaces()?.into_iter().map(Into::into).collect()); l.append(&mut db.list_workspaces()?.into_iter().map(Into::into).collect());
l.append(&mut db.list_key_values()?.into_iter().map(Into::into).collect()); l.append(&mut db.list_key_values()?.into_iter().map(Into::into).collect());
} }
let plugins = { let plugins = {
let db = host.db(); let db = host.db()?;
db.list_plugins()? db.list_plugins()?
}; };
@@ -112,7 +112,7 @@ 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() {
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_ensure_base(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());
@@ -132,7 +132,7 @@ 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 db = host.db()?;
let workspace = db.get_workspace(&req.workspace_id)?; let workspace = db.get_workspace(&req.workspace_id)?;
Ok(db.get_or_create_workspace_meta(&workspace.id)?) Ok(db.get_or_create_workspace_meta(&workspace.id)?)
} }
@@ -141,14 +141,16 @@ 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
.db()?
.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.db()?.delete_all_http_responses_for_request(&req.request_id, &host.update_source())?;
Ok(()) Ok(())
} }
@@ -157,7 +159,7 @@ pub async fn cmd_ws_delete_connections<H: Host>(
req: CmdWsDeleteConnectionsReq, req: CmdWsDeleteConnectionsReq,
) -> Result<()> { ) -> Result<()> {
Ok(host Ok(host
.db() .db()?
.delete_all_websocket_connections_for_request(&req.request_id, &host.update_source())?) .delete_all_websocket_connections_for_request(&req.request_id, &host.update_source())?)
} }
+1 -1
View File
@@ -10,7 +10,7 @@ pub async fn cmd_plugin_info<H: PluginHost>(
host: H, host: H,
req: CmdPluginInfoReq, req: CmdPluginInfoReq,
) -> Result<PluginMetadata> { ) -> Result<PluginMetadata> {
let plugin = host.db().get_plugin(&req.id)?; let plugin = host.db()?.get_plugin(&req.id)?;
if let Some(metadata) = host.loaded_plugin_metadata(&plugin.directory).await { if let Some(metadata) = host.loaded_plugin_metadata(&plugin.directory).await {
return Ok(metadata); return Ok(metadata);
} }
+2 -2
View File
@@ -64,9 +64,9 @@ pub(crate) async fn render_form_values<H: PluginHost>(
}; };
let environment_chain = let environment_chain =
host.db().resolve_environments(&workspace_id, folder_id.as_deref(), environment_id)?; host.db()?.resolve_environments(&workspace_id, folder_id.as_deref(), environment_id)?;
let cb = host.template_callback(purpose); let cb = host.template_callback(purpose).await?;
let rendered = let rendered =
render_json_value(serde_json::to_value(&values)?, environment_chain, &cb, options).await?; render_json_value(serde_json::to_value(&values)?, environment_chain, &cb, options).await?;
+4 -4
View File
@@ -41,7 +41,7 @@ pub async fn cmd_get_http_response_events<H: Host>(
host: H, host: H,
req: CmdGetHttpResponseEventsReq, req: CmdGetHttpResponseEventsReq,
) -> Result<Vec<HttpResponseEvent>> { ) -> Result<Vec<HttpResponseEvent>> {
let events: Vec<HttpResponseEvent> = host.db().list_http_response_events(&req.response_id)?; let events: Vec<HttpResponseEvent> = host.db()?.list_http_response_events(&req.response_id)?;
Ok(events) Ok(events)
} }
@@ -55,7 +55,7 @@ pub async fn cmd_http_response_body_path<H: Host>(
host: H, host: H,
req: CmdHttpResponseBodyPathReq, req: CmdHttpResponseBodyPathReq,
) -> Result<Option<String>> { ) -> Result<Option<String>> {
let location = locate_response_body(&host.db(), &req.response_id)?; let location = locate_response_body(&host.db()?, &req.response_id)?;
Ok(location.path.map(|p| p.to_string_lossy().to_string())) Ok(location.path.map(|p| p.to_string_lossy().to_string()))
} }
@@ -64,7 +64,7 @@ pub async fn cmd_http_request_body<H: Host>(
req: CmdHttpRequestBodyReq, req: CmdHttpRequestBodyReq,
) -> Result<Option<Vec<u8>>> { ) -> Result<Option<Vec<u8>>> {
let body_id = format!("{}.request", req.response_id); let body_id = format!("{}.request", req.response_id);
let chunks = host.blobs().get_chunks(&body_id)?; let chunks = host.blobs()?.get_chunks(&body_id)?;
if chunks.is_empty() { if chunks.is_empty() {
return Ok(None); return Ok(None);
@@ -76,7 +76,7 @@ pub async fn cmd_http_request_body<H: Host>(
} }
pub async fn cmd_save_response<H: Host>(host: H, req: CmdSaveResponseReq) -> Result<()> { pub async fn cmd_save_response<H: Host>(host: H, req: CmdSaveResponseReq) -> Result<()> {
let response = host.db().get_http_response(&req.response_id)?; let response = host.db()?.get_http_response(&req.response_id)?;
let body_path = let body_path =
response.body_path.ok_or(Error::Generic("Response does not have a body".to_string()))?; response.body_path.ok_or(Error::Generic("Response does not have a body".to_string()))?;
+3 -3
View File
@@ -20,8 +20,8 @@ pub async fn cmd_render_template<H: PluginHost>(
req: CmdRenderTemplateReq, req: CmdRenderTemplateReq,
) -> Result<String> { ) -> Result<String> {
let environment_chain = let environment_chain =
host.db().resolve_environments(&req.workspace_id, None, req.environment_id.as_deref())?; host.db()?.resolve_environments(&req.workspace_id, None, req.environment_id.as_deref())?;
let cb = host.template_callback(req.purpose.unwrap_or(RenderPurpose::Preview)); let cb = host.template_callback(req.purpose.unwrap_or(RenderPurpose::Preview)).await?;
let options = RenderOptions { let options = RenderOptions {
// A preview that throws would show the user an error where they expect // A preview that throws would show the user an error where they expect
// to see the value so far, so callers rendering *into the UI* ask for // to see the value so far, so callers rendering *into the UI* ask for
@@ -41,7 +41,7 @@ pub async fn cmd_template_tokens_to_string<H: PluginHost>(
host: H, host: H,
req: CmdTemplateTokensToStringReq, req: CmdTemplateTokensToStringReq,
) -> Result<String> { ) -> Result<String> {
let cb = host.template_callback(RenderPurpose::Preview); let cb = host.template_callback(RenderPurpose::Preview).await?;
Ok(transform_args(req.tokens, &cb)?.to_string()) Ok(transform_args(req.tokens, &cb)?.to_string())
} }
+15 -7
View File
@@ -141,13 +141,13 @@ async fn writes_carry_the_client_id() {
// Deletes cascade inside a transaction; make sure that path works with no // Deletes cascade inside a transaction; make sure that path works with no
// host doing anything special around it. // host doing anything special around it.
let workspace = host.db().get_workspace(&id).expect("get workspace"); let workspace = host.db().unwrap().get_workspace(&id).expect("get workspace");
let deleted = let deleted =
models_delete(host.clone(), ModelsDeleteReq { model: AnyModel::Workspace(workspace) }) models_delete(host.clone(), ModelsDeleteReq { model: AnyModel::Workspace(workspace) })
.await .await
.expect("delete"); .expect("delete");
assert_eq!(deleted, id); assert_eq!(deleted, id);
assert!(host.db().get_workspace(&id).is_err(), "workspace should be gone"); assert!(host.db().unwrap().get_workspace(&id).is_err(), "workspace should be gone");
} }
#[tokio::test] #[tokio::test]
@@ -250,8 +250,11 @@ impl PluginHost for SingleThreadedHost {
Err(yaak_commands::Error::Generic("no plugin runtime on this host".into())) Err(yaak_commands::Error::Generic("no plugin runtime on this host".into()))
} }
fn template_callback(&self, _purpose: RenderPurpose) -> impl TemplateCallback { async fn template_callback(
NoTemplateFunctions &self,
_purpose: RenderPurpose,
) -> yaak_commands::Result<impl TemplateCallback> {
Ok(NoTemplateFunctions)
} }
async fn template_function_summaries( async fn template_function_summaries(
@@ -404,6 +407,7 @@ async fn a_single_threaded_host_can_implement_the_trait() {
// 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() .db()
.unwrap()
.upsert_environment( .upsert_environment(
&Environment { &Environment {
workspace_id: id.clone(), workspace_id: id.clone(),
@@ -436,7 +440,7 @@ async fn a_single_threaded_host_can_implement_the_trait() {
// The delete path too, since it is the one that used to reach for a // The delete path too, since it is the one that used to reach for a
// blocking thread this host does not have. // blocking thread this host does not have.
let workspace = host.db().get_workspace(&id).expect("get workspace"); let workspace = host.db().unwrap().get_workspace(&id).expect("get workspace");
let deleted = models_delete(host, ModelsDeleteReq { model: AnyModel::Workspace(workspace) }) let deleted = models_delete(host, ModelsDeleteReq { model: AnyModel::Workspace(workspace) })
.await .await
.expect("delete"); .expect("delete");
@@ -457,12 +461,14 @@ async fn auth_values_are_rendered_before_the_host_sees_them() {
let workspace = host let workspace = host
.db() .db()
.unwrap()
.upsert_workspace( .upsert_workspace(
&Workspace { name: "Auth".to_string(), ..Default::default() }, &Workspace { name: "Auth".to_string(), ..Default::default() },
&host.update_source(), &host.update_source(),
) )
.expect("workspace"); .expect("workspace");
host.db() host.db()
.unwrap()
.upsert_environment( .upsert_environment(
&Environment { &Environment {
workspace_id: workspace.id.clone(), workspace_id: workspace.id.clone(),
@@ -479,7 +485,7 @@ async fn auth_values_are_rendered_before_the_host_sees_them() {
) )
.expect("environment"); .expect("environment");
let environment = let environment =
host.db().list_environments_ensure_base(&workspace.id).expect("list").remove(0); host.db().unwrap().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()));
@@ -519,12 +525,14 @@ async fn template_function_values_are_rendered_before_the_host_sees_them() {
let workspace = host let workspace = host
.db() .db()
.unwrap()
.upsert_workspace( .upsert_workspace(
&Workspace { name: "Functions".to_string(), ..Default::default() }, &Workspace { name: "Functions".to_string(), ..Default::default() },
&host.update_source(), &host.update_source(),
) )
.expect("workspace"); .expect("workspace");
host.db() host.db()
.unwrap()
.upsert_environment( .upsert_environment(
&Environment { &Environment {
workspace_id: workspace.id.clone(), workspace_id: workspace.id.clone(),
@@ -541,7 +549,7 @@ async fn template_function_values_are_rendered_before_the_host_sees_them() {
) )
.expect("environment"); .expect("environment");
let environment = let environment =
host.db().list_environments_ensure_base(&workspace.id).expect("list").remove(0); host.db().unwrap().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()));
+6 -4
View File
@@ -51,7 +51,7 @@ impl EncryptionManager {
pub fn set_human_key(&self, workspace_id: &str, human_key: &str) -> Result<WorkspaceMeta> { pub fn set_human_key(&self, workspace_id: &str, human_key: &str) -> Result<WorkspaceMeta> {
let wkey = WorkspaceKey::from_human(human_key)?; let wkey = WorkspaceKey::from_human(human_key)?;
let workspace = self.query_manager.connect().get_workspace(workspace_id)?; let workspace = self.query_manager.connect()?.get_workspace(workspace_id)?;
let encryption_key_challenge = match workspace.encryption_key_challenge { let encryption_key_challenge = match workspace.encryption_key_challenge {
None => return self.set_workspace_key(workspace_id, &wkey), None => return self.set_workspace_key(workspace_id, &wkey),
Some(c) => c, Some(c) => c,
@@ -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.connect()?.get_or_create_workspace_meta(workspace_id)?;
// Already exists // Already exists
if let Some(_) = workspace_meta.encryption_key { if let Some(_) = workspace_meta.encryption_key {
@@ -152,8 +152,10 @@ impl EncryptionManager {
} }
}; };
let db = self.query_manager.connect(); // Scoped so the pooled connection is back before `get_master_key` below, which
let workspace_meta = db.get_or_create_workspace_meta(workspace_id)?; // can block on the OS keyring for as long as it likes.
let workspace_meta =
self.query_manager.connect()?.get_or_create_workspace_meta(workspace_id)?;
let key = match workspace_meta.encryption_key { let key = match workspace_meta.encryption_key {
None => return Err(MissingWorkspaceKey), None => return Err(MissingWorkspaceKey),
+5
View File
@@ -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>, };
+1 -1
View File
@@ -210,7 +210,7 @@ fn field_to_type_or_ref(root_name: &str, field: FieldDescriptor) -> JsonSchemaEn
// [Protocol Buffers Well-Known Types]: https://protobuf.dev/reference/protobuf/google.protobuf/ // [Protocol Buffers Well-Known Types]: https://protobuf.dev/reference/protobuf/google.protobuf/
"google.protobuf.FieldMask" => JsonSchemaEntry::string(), "google.protobuf.FieldMask" => JsonSchemaEntry::string(),
"google.protobuf.Timestamp" => JsonSchemaEntry::string_with_format("date-time"), "google.protobuf.Timestamp" => JsonSchemaEntry::string_with_format("date-time"),
"google.protobuf.Duration" => JsonSchemaEntry::string(), "google.protobuf.Duration" => JsonSchemaEntry::string_with_format("duration"),
"google.protobuf.StringValue" => JsonSchemaEntry::string(), "google.protobuf.StringValue" => JsonSchemaEntry::string(),
"google.protobuf.BytesValue" => JsonSchemaEntry::string_with_format("byte"), "google.protobuf.BytesValue" => JsonSchemaEntry::string_with_format("byte"),
"google.protobuf.Int32Value" => JsonSchemaEntry::number("int32"), "google.protobuf.Int32Value" => JsonSchemaEntry::number("int32"),
+4 -4
View File
@@ -77,7 +77,7 @@ 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 db = query_manager.connect().unwrap();
let source = &UpdateSource::Background; let source = &UpdateSource::Background;
let workspace = db let workspace = db
@@ -117,14 +117,14 @@ mod tests {
#[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(); let db = query_manager.connect().unwrap();
{ {
let blob_ctx = blob_manager.connect(); let blob_ctx = blob_manager.connect().unwrap();
blob_ctx.insert_chunk(&BodyChunk::new("rs_gone", 0, b"dead".to_vec())).unwrap(); blob_ctx.insert_chunk(&BodyChunk::new("rs_gone", 0, b"dead".to_vec())).unwrap();
} }
on_launch(&Host::owner(), &db, &blob_manager).unwrap(); on_launch(&Host::owner(), &db, &blob_manager).unwrap();
assert!(!blob_manager.connect().body_exists("rs_gone").unwrap()); assert!(!blob_manager.connect().unwrap().body_exists("rs_gone").unwrap());
} }
} }
+3
View File
@@ -27,3 +27,6 @@ yaak-templates = { path = "../yaak-templates", default-features = false }
[target.'cfg(not(target_arch = "wasm32"))'.dependencies] [target.'cfg(not(target_arch = "wasm32"))'.dependencies]
r2d2 = "0.8.10" r2d2 = "0.8.10"
r2d2_sqlite = { version = "0.32" } r2d2_sqlite = { version = "0.32" }
[dev-dependencies]
tempfile = "3"
+30
View File
@@ -12,6 +12,7 @@ export type AnyModel =
| HttpRequest | HttpRequest
| HttpResponse | HttpResponse
| HttpResponseEvent | HttpResponseEvent
| ImportSource
| KeyValue | KeyValue
| Plugin | Plugin
| Settings | Settings
@@ -336,6 +337,35 @@ export type HttpUrlParameter = {
export type HttpVersion = "auto" | "http1" | "http2"; export type HttpVersion = "auto" | "http1" | "http2";
export type ImportSource = {
model: "import_source";
id: string;
createdAt: string;
updatedAt: string;
workspaceId: string;
importer: string;
origin: string;
originLabel: string;
lastImportedAt: string;
};
export type ImportSourceResource = {
model: "import_source_resource";
createdAt: string;
updatedAt: string;
importSourceId: string;
sourceKey: string;
modelType: 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 };
export type InheritedHttpVersionSetting = { enabled?: boolean; value: HttpVersion }; export type InheritedHttpVersionSetting = { enabled?: boolean; value: HttpVersion };
+105 -2
View File
@@ -1,4 +1,107 @@
// 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";
/**
* Where a staged import will be committed.
*
* The destination workspace and optional folder IDs are captured in the plan so the preview describes
* the exact destination that confirmation will use.
*/
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.
*/
export type ImportOrigin = {
/**
* The absolute file path or URL the contents were read from.
*/
origin: string;
label: string;
};
export type ImportPlan = {
importer: string;
destination: ImportDestination;
resources: BatchUpsertResult;
warnings: Array<ImportPlanWarning>;
/**
* Stable source key for every model in `resources`, keyed by its planned ID.
*/
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"
| "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>;
};
/**
* Extra context for an action that would otherwise be indistinguishable from its plain form.
*/
export type ImportPlanReason = "moved_into_ignored_folder";
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.
*/
export type ImportResourceType =
| "environment"
| "folder"
| "grpc_request"
| "http_request"
| "websocket_request"
| "workspace";
+1
View File
@@ -12,6 +12,7 @@ export function newStoreData(): ModelStoreData {
http_request: {}, http_request: {},
http_response: {}, http_response: {},
http_response_event: {}, http_response_event: {},
import_source: {},
key_value: {}, key_value: {},
plugin: {}, plugin: {},
settings: {}, settings: {},
@@ -0,0 +1,25 @@
CREATE TABLE import_sources
(
id TEXT NOT NULL PRIMARY KEY,
model TEXT DEFAULT 'import_source' NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
workspace_id TEXT NOT NULL,
importer TEXT NOT NULL,
origin TEXT NOT NULL,
origin_label TEXT NOT NULL,
last_imported_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL
);
CREATE TABLE import_source_resources
(
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 NOT NULL,
snapshot TEXT NOT NULL,
PRIMARY KEY (import_source_id, source_key)
);
@@ -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;
+12 -12
View File
@@ -36,9 +36,9 @@ impl BlobManager {
Self { pool } Self { pool }
} }
pub fn connect(&self) -> BlobContext { pub fn connect(&self) -> Result<BlobContext> {
let conn = self.pool.get().expect("Failed to get blob DB connection from pool"); let conn = crate::pool::acquire(&self.pool, "blob")?;
BlobContext { conn } Ok(BlobContext { conn })
} }
} }
@@ -208,7 +208,7 @@ mod tests {
fn test_insert_and_get_chunks() { fn test_insert_and_get_chunks() {
let pool = create_test_pool(); let pool = create_test_pool();
let manager = BlobManager::new(pool); let manager = BlobManager::new(pool);
let ctx = manager.connect(); let ctx = manager.connect().unwrap();
let body_id = "rs_test123.request"; let body_id = "rs_test123.request";
let chunk1 = BodyChunk::new(body_id, 0, b"Hello, ".to_vec()); let chunk1 = BodyChunk::new(body_id, 0, b"Hello, ".to_vec());
@@ -229,7 +229,7 @@ mod tests {
fn test_get_chunks_ordered_by_index() { fn test_get_chunks_ordered_by_index() {
let pool = create_test_pool(); let pool = create_test_pool();
let manager = BlobManager::new(pool); let manager = BlobManager::new(pool);
let ctx = manager.connect(); let ctx = manager.connect().unwrap();
let body_id = "rs_test123.request"; let body_id = "rs_test123.request";
@@ -249,7 +249,7 @@ mod tests {
fn test_delete_chunks() { fn test_delete_chunks() {
let pool = create_test_pool(); let pool = create_test_pool();
let manager = BlobManager::new(pool); let manager = BlobManager::new(pool);
let ctx = manager.connect(); let ctx = manager.connect().unwrap();
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(); ctx.insert_chunk(&BodyChunk::new(body_id, 0, b"data".to_vec())).unwrap();
@@ -266,7 +266,7 @@ mod tests {
fn test_delete_chunks_like() { fn test_delete_chunks_like() {
let pool = create_test_pool(); let pool = create_test_pool();
let manager = BlobManager::new(pool); let manager = BlobManager::new(pool);
let ctx = manager.connect(); let ctx = manager.connect().unwrap();
// 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(); ctx.insert_chunk(&BodyChunk::new("rs_abc.request", 0, b"req".to_vec())).unwrap();
@@ -288,7 +288,7 @@ mod tests {
fn test_get_body_size() { fn test_get_body_size() {
let pool = create_test_pool(); let pool = create_test_pool();
let manager = BlobManager::new(pool); let manager = BlobManager::new(pool);
let ctx = manager.connect(); let ctx = manager.connect().unwrap();
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(); ctx.insert_chunk(&BodyChunk::new(body_id, 0, b"Hello".to_vec())).unwrap();
@@ -302,7 +302,7 @@ mod tests {
fn test_get_body_size_empty() { fn test_get_body_size_empty() {
let pool = create_test_pool(); let pool = create_test_pool();
let manager = BlobManager::new(pool); let manager = BlobManager::new(pool);
let ctx = manager.connect(); let ctx = manager.connect().unwrap();
let size = ctx.get_body_size("nonexistent").unwrap(); let size = ctx.get_body_size("nonexistent").unwrap();
assert_eq!(size, 0); assert_eq!(size, 0);
@@ -312,7 +312,7 @@ mod tests {
fn test_body_exists() { fn test_body_exists() {
let pool = create_test_pool(); let pool = create_test_pool();
let manager = BlobManager::new(pool); let manager = BlobManager::new(pool);
let ctx = manager.connect(); let ctx = manager.connect().unwrap();
assert!(!ctx.body_exists("rs_test.request").unwrap()); assert!(!ctx.body_exists("rs_test.request").unwrap());
@@ -325,7 +325,7 @@ mod tests {
fn test_multiple_bodies_isolated() { fn test_multiple_bodies_isolated() {
let pool = create_test_pool(); let pool = create_test_pool();
let manager = BlobManager::new(pool); let manager = BlobManager::new(pool);
let ctx = manager.connect(); let ctx = manager.connect().unwrap();
ctx.insert_chunk(&BodyChunk::new("body1", 0, b"data1".to_vec())).unwrap(); ctx.insert_chunk(&BodyChunk::new("body1", 0, b"data1".to_vec())).unwrap();
ctx.insert_chunk(&BodyChunk::new("body2", 0, b"data2".to_vec())).unwrap(); ctx.insert_chunk(&BodyChunk::new("body2", 0, b"data2".to_vec())).unwrap();
@@ -343,7 +343,7 @@ mod tests {
fn test_large_chunk() { fn test_large_chunk() {
let pool = create_test_pool(); let pool = create_test_pool();
let manager = BlobManager::new(pool); let manager = BlobManager::new(pool);
let ctx = manager.connect(); let ctx = manager.connect().unwrap();
// 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();
+12
View File
@@ -9,6 +9,18 @@ pub enum Error {
#[error("SQL Pool error: {0}")] #[error("SQL Pool error: {0}")]
SqlPoolError(#[from] yaak_database::PoolError), SqlPoolError(#[from] yaak_database::PoolError),
#[error(
"Timed out after {waited_ms}ms waiting for a {what} database connection ({connections} open, {idle} idle)"
)]
PoolTimeout {
what: &'static str,
waited_ms: u128,
connections: u32,
idle: u32,
#[source]
source: yaak_database::PoolError,
},
#[error("Database error: {0}")] #[error("Database error: {0}")]
Database(String), Database(String),
+8 -5
View File
@@ -17,6 +17,7 @@ pub mod migrate;
pub mod models; pub mod models;
pub mod models_ops; pub mod models_ops;
pub mod path_placeholders; pub mod path_placeholders;
mod pool;
pub mod queries; pub mod queries;
pub mod query_manager; pub mod query_manager;
pub mod render; pub mod render;
@@ -108,12 +109,14 @@ 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 // Main database pool. Sized for concurrent in-flight commands, not concurrent app
// features — connections are held per-statement, so even heavy fan-out (e.g. many // features: connections are held per-statement, but one command can nest a couple of
// gRPC streams) only needs a handful at once. Keep max_size modest: WAL connections // them, and since every frontend command dispatches as its own task they all land at
// hold ~3 file descriptors each, and macOS GUI apps get a 256 fd soft limit. // once. Only `min_idle` is paid up front — r2d2 opens the rest on demand — and the
// app raises its open-file limit to 10240 at startup, so the old 256 fd ceiling that
// kept this small no longer applies.
info!("Initializing app database {db_path:?}"); info!("Initializing app database {db_path:?}");
let pool = open::file_pool(db_path, 20, 2)?; let pool = open::file_pool(db_path, 50, 2)?;
migrate_db(&pool)?; migrate_db(&pool)?;
info!("Initializing blobs database {blob_path:?}"); info!("Initializing blobs database {blob_path:?}");
+123
View File
@@ -3022,6 +3022,127 @@ impl<'s> TryFrom<&Row<'s>> for PluginKeyValue {
} }
} }
#[derive(Debug, Clone, Serialize, Deserialize, Default, TS)]
#[serde(default, rename_all = "camelCase")]
#[ts(export, export_to = "gen_models.ts")]
#[enum_def(table_name = "import_sources")]
pub struct ImportSource {
#[ts(type = "\"import_source\"")]
pub model: String,
pub id: String,
pub created_at: NaiveDateTime,
pub updated_at: NaiveDateTime,
pub workspace_id: String,
pub importer: String,
pub origin: String,
pub origin_label: String,
pub last_imported_at: NaiveDateTime,
}
impl UpsertModelInfo for ImportSource {
fn table_name() -> impl IntoTableRef + IntoIden {
ImportSourceIden::Table
}
fn id_column() -> impl IntoIden + Eq + Clone {
ImportSourceIden::Id
}
fn generate_id() -> String {
generate_prefixed_id("im")
}
fn order_by() -> (impl IntoColumnRef, Order) {
(ImportSourceIden::CreatedAt, Desc)
}
fn get_id(&self) -> String {
self.id.clone()
}
fn insert_values(
self,
source: &UpdateSource,
) -> DbResult<Vec<(impl IntoIden + Eq, impl Into<SimpleExpr>)>> {
use ImportSourceIden::*;
Ok(vec![
(CreatedAt, upsert_date(source, self.created_at)),
(UpdatedAt, upsert_date(source, self.updated_at)),
(WorkspaceId, self.workspace_id.into()),
(Importer, self.importer.into()),
(Origin, self.origin.into()),
(OriginLabel, self.origin_label.into()),
(LastImportedAt, self.last_imported_at.into()),
])
}
fn update_columns() -> Vec<impl IntoIden> {
vec![
ImportSourceIden::UpdatedAt,
ImportSourceIden::Importer,
ImportSourceIden::Origin,
ImportSourceIden::OriginLabel,
ImportSourceIden::LastImportedAt,
]
}
fn from_row(row: &Row) -> rusqlite::Result<Self>
where
Self: Sized,
{
Ok(Self {
id: row.get("id")?,
model: row.get("model")?,
created_at: row.get("created_at")?,
updated_at: row.get("updated_at")?,
workspace_id: row.get("workspace_id")?,
importer: row.get("importer")?,
origin: row.get("origin")?,
origin_label: row.get("origin_label")?,
last_imported_at: row.get("last_imported_at")?,
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize, Default, TS)]
#[serde(default, rename_all = "camelCase")]
#[ts(export, export_to = "gen_models.ts")]
#[enum_def(table_name = "import_source_resources")]
pub struct ImportSourceResource {
#[ts(type = "\"import_source_resource\"")]
pub model: String,
pub created_at: NaiveDateTime,
pub updated_at: NaiveDateTime,
pub import_source_id: String,
pub source_key: String,
pub model_type: String,
/// `None` once the user has decided not to import this key
#[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 {
type Error = rusqlite::Error;
fn try_from(r: &Row<'s>) -> std::result::Result<Self, Self::Error> {
Ok(Self {
model: r.get("model")?,
created_at: r.get("created_at")?,
updated_at: r.get("updated_at")?,
import_source_id: r.get("import_source_id")?,
source_key: r.get("source_key")?,
model_type: r.get("model_type")?,
model_id: r.get("model_id")?,
content_hash: r.get("content_hash")?,
})
}
}
/// Only used as a `from_row` fallback for an unparseable settings column. The /// Only used as a `from_row` fallback for an unparseable settings column. The
/// value a *new* model gets comes from that model's `Default` impl. /// value a *new* model gets comes from that model's `Default` impl.
fn default_request_message_size_setting() -> InheritedIntSetting { fn default_request_message_size_setting() -> InheritedIntSetting {
@@ -3093,6 +3214,7 @@ define_any_model! {
HttpRequest, HttpRequest,
HttpResponse, HttpResponse,
HttpResponseEvent, HttpResponseEvent,
ImportSource,
KeyValue, KeyValue,
Plugin, Plugin,
Settings, Settings,
@@ -3125,6 +3247,7 @@ impl<'de> Deserialize<'de> for AnyModel {
Some(m) if m == "http_request" => HttpRequest(fv(value).unwrap()), Some(m) if m == "http_request" => HttpRequest(fv(value).unwrap()),
Some(m) if m == "http_response" => HttpResponse(fv(value).unwrap()), Some(m) if m == "http_response" => HttpResponse(fv(value).unwrap()),
Some(m) if m == "http_response_event" => HttpResponseEvent(fv(value).unwrap()), Some(m) if m == "http_response_event" => HttpResponseEvent(fv(value).unwrap()),
Some(m) if m == "import_source" => ImportSource(fv(value).unwrap()),
Some(m) if m == "key_value" => KeyValue(fv(value).unwrap()), Some(m) if m == "key_value" => KeyValue(fv(value).unwrap()),
Some(m) if m == "plugin" => Plugin(fv(value).unwrap()), Some(m) if m == "plugin" => Plugin(fv(value).unwrap()),
Some(m) if m == "settings" => Settings(fv(value).unwrap()), Some(m) if m == "settings" => Settings(fv(value).unwrap()),
+48
View File
@@ -0,0 +1,48 @@
//! One way in and out of a connection pool, so every acquisition is timed the same way.
//!
//! A pool that cannot hand out a connection fails with a timeout and nothing else: r2d2
//! reports `Error(None)` whether all the connections are checked out or none could be
//! opened in the first place. Those have nothing to do with each other, so the state of
//! the pool at the moment it gave up rides along in the error and in the log line.
use crate::error::{Error, Result};
use log::warn;
use std::time::{Duration, Instant};
use yaak_database::{SqliteConn, SqlitePool, pool_status};
/// Long enough that a healthy app never logs, short enough to catch a pool going bad
/// well before the acquire timeout turns it into an error.
const SLOW_ACQUIRE: Duration = Duration::from_secs(1);
pub(crate) fn acquire(pool: &SqlitePool, what: &'static str) -> Result<SqliteConn> {
let started = Instant::now();
let result = pool.get();
let waited = started.elapsed();
match result {
Ok(conn) => {
if waited >= SLOW_ACQUIRE {
warn!(
"Waited {}ms for a {what} connection ({})",
waited.as_millis(),
pool_status(pool)
);
}
Ok(conn)
}
Err(source) => {
let status = pool_status(pool);
warn!(
"Gave up after {}ms waiting for a {what} connection ({status})",
waited.as_millis()
);
Err(Error::PoolTimeout {
what,
waited_ms: waited.as_millis(),
connections: status.connections,
idle: status.idle,
source,
})
}
}
}
@@ -190,7 +190,7 @@ mod tests {
#[test] #[test]
fn request_resolution_preserves_duplicate_request_headers() { fn request_resolution_preserves_duplicate_request_headers() {
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 db = query_manager.connect().unwrap();
let workspace = db.list_workspaces().expect("Failed to list workspaces").remove(0); let workspace = db.list_workspaces().expect("Failed to list workspaces").remove(0);
let request = HttpRequest { let request = HttpRequest {
workspace_id: workspace.id, workspace_id: workspace.id,
@@ -225,7 +225,7 @@ 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 db = query_manager.connect().unwrap();
let workspace = db let workspace = db
.upsert_workspace( .upsert_workspace(
@@ -57,7 +57,7 @@ impl<'a> ClientDb<'a> {
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 mut deleted = 0;
let blob_ctx = blobs.connect(); let blob_ctx = blobs.connect()?;
for body_id in blob_ctx.list_body_ids()? { for body_id in blob_ctx.list_body_ids()? {
let response_id = body_id.split('.').next().unwrap_or_default(); let response_id = body_id.split('.').next().unwrap_or_default();
if self.find_optional::<HttpResponse>(HttpResponseIden::Id, response_id).is_some() { if self.find_optional::<HttpResponse>(HttpResponseIden::Id, response_id).is_some() {
@@ -138,7 +138,7 @@ 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 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_ctx.delete_chunks(&body_id) {
error!("Failed to delete request body blobs: {}", e); error!("Failed to delete request body blobs: {}", e);
@@ -224,14 +224,14 @@ 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 db = query_manager.connect().unwrap();
let live = seed_live_response(&db, &blob_manager); let live = seed_live_response(&db, &blob_manager);
let live_request_body_id = format!("{}.request", live.id); let live_request_body_id = format!("{}.request", live.id);
{ {
// Scope the connection: the in-memory pool only has one, and the GC // Scope the connection: the in-memory pool only has one, and the GC
// needs to take it // needs to take it
let blob_ctx = blob_manager.connect(); let blob_ctx = blob_manager.connect().unwrap();
blob_ctx.insert_chunk(&BodyChunk::new(&live.id, 0, b"live".to_vec())).unwrap(); blob_ctx.insert_chunk(&BodyChunk::new(&live.id, 0, b"live".to_vec())).unwrap();
blob_ctx blob_ctx
.insert_chunk(&BodyChunk::new(&live_request_body_id, 0, b"live".to_vec())) .insert_chunk(&BodyChunk::new(&live_request_body_id, 0, b"live".to_vec()))
@@ -245,7 +245,7 @@ mod tests {
.expect("Failed to GC response body blobs"); .expect("Failed to GC response body blobs");
assert_eq!(deleted, 2); assert_eq!(deleted, 2);
let blob_ctx = blob_manager.connect(); let blob_ctx = blob_manager.connect().unwrap();
assert!(blob_ctx.body_exists(&live.id).unwrap()); assert!(blob_ctx.body_exists(&live.id).unwrap());
assert!(blob_ctx.body_exists(&live_request_body_id).unwrap()); assert!(blob_ctx.body_exists(&live_request_body_id).unwrap());
assert!(!blob_ctx.body_exists("rs_gone").unwrap()); assert!(!blob_ctx.body_exists("rs_gone").unwrap());
@@ -255,14 +255,14 @@ 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 db = query_manager.connect().unwrap();
let live = seed_live_response(&db, &blob_manager); let live = seed_live_response(&db, &blob_manager);
let live_body_id = format!("{}.request", live.id); let live_body_id = format!("{}.request", live.id);
{ {
// Scope the connection: the in-memory pool only has one, and the GC // Scope the connection: the in-memory pool only has one, and the GC
// needs to take it // needs to take it
let blob_ctx = blob_manager.connect(); let blob_ctx = blob_manager.connect().unwrap();
blob_ctx.insert_chunk(&BodyChunk::new(&live_body_id, 0, b"live".to_vec())).unwrap(); 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(); blob_ctx.insert_chunk(&BodyChunk::new("rs_gone.request", 0, b"dead".to_vec())).unwrap();
} }
@@ -278,7 +278,7 @@ mod tests {
assert_eq!(deleted, 2); assert_eq!(deleted, 2);
// Live data survives, orphans are gone // Live data survives, orphans are gone
let blob_ctx = blob_manager.connect(); let blob_ctx = blob_manager.connect().unwrap();
assert!(blob_ctx.body_exists(&live_body_id).unwrap()); assert!(blob_ctx.body_exists(&live_body_id).unwrap());
assert!(!blob_ctx.body_exists("rs_gone.request").unwrap()); assert!(!blob_ctx.body_exists("rs_gone.request").unwrap());
assert!(dir.join(&live.id).exists()); assert!(dir.join(&live.id).exists());
@@ -0,0 +1,94 @@
use crate::client_db::ClientDb;
use crate::error::Result;
use crate::models::{ImportSourceResource, ImportSourceResourceIden};
use sea_query::ExprTrait;
use sea_query::Keyword::CurrentTimestamp;
use sea_query::{Asterisk, Cond, Expr, OnConflict, Query, SqliteQueryBuilder};
use sea_query_rusqlite::RusqliteBinder;
impl<'a> ClientDb<'a> {
pub fn list_import_source_resources(
&self,
import_source_id: &str,
) -> Result<Vec<ImportSourceResource>> {
let (sql, params) = Query::select()
.from(ImportSourceResourceIden::Table)
.column(Asterisk)
.cond_where(Expr::col(ImportSourceResourceIden::ImportSourceId).eq(import_source_id))
.build_rusqlite(SqliteQueryBuilder);
let mut stmt = self.conn().prepare(sql.as_str())?;
let items = stmt.query_map(&*params.as_params(), |row| row.try_into())?;
Ok(items.filter_map(|v| v.ok()).collect())
}
pub fn upsert_import_source_resource(
&self,
resource: &ImportSourceResource,
) -> Result<ImportSourceResource> {
let (sql, params) = Query::insert()
.into_table(ImportSourceResourceIden::Table)
.columns([
ImportSourceResourceIden::CreatedAt,
ImportSourceResourceIden::UpdatedAt,
ImportSourceResourceIden::ImportSourceId,
ImportSourceResourceIden::SourceKey,
ImportSourceResourceIden::ModelType,
ImportSourceResourceIden::ModelId,
ImportSourceResourceIden::ContentHash,
])
.values_panic([
CurrentTimestamp.into(),
CurrentTimestamp.into(),
resource.import_source_id.as_str().into(),
resource.source_key.as_str().into(),
resource.model_type.as_str().into(),
resource.model_id.clone().into(),
resource.content_hash.clone().into(),
])
.on_conflict(
OnConflict::columns([
ImportSourceResourceIden::ImportSourceId,
ImportSourceResourceIden::SourceKey,
])
.update_columns([
ImportSourceResourceIden::UpdatedAt,
ImportSourceResourceIden::ModelType,
ImportSourceResourceIden::ModelId,
ImportSourceResourceIden::ContentHash,
])
.to_owned(),
)
.returning_all()
.build_rusqlite(SqliteQueryBuilder);
let mut stmt = self.conn().prepare(sql.as_str())?;
let m = stmt.query_row(&*params.as_params(), |row| row.try_into())?;
Ok(m)
}
pub fn delete_import_source_resource(
&self,
import_source_id: &str,
source_key: &str,
) -> Result<()> {
let (sql, params) = Query::delete()
.from_table(ImportSourceResourceIden::Table)
.cond_where(
Cond::all()
.add(Expr::col(ImportSourceResourceIden::ImportSourceId).eq(import_source_id))
.add(Expr::col(ImportSourceResourceIden::SourceKey).eq(source_key)),
)
.build_rusqlite(SqliteQueryBuilder);
self.conn().execute(sql.as_str(), &*params.as_params())?;
Ok(())
}
pub fn delete_import_source_resources(&self, import_source_id: &str) -> Result<()> {
let (sql, params) = Query::delete()
.from_table(ImportSourceResourceIden::Table)
.cond_where(Expr::col(ImportSourceResourceIden::ImportSourceId).eq(import_source_id))
.build_rusqlite(SqliteQueryBuilder);
self.conn().execute(sql.as_str(), &*params.as_params())?;
Ok(())
}
}
@@ -0,0 +1,45 @@
use crate::client_db::ClientDb;
use crate::error::Result;
use crate::models::{ImportSource, ImportSourceIden};
use crate::util::UpdateSource;
impl<'a> ClientDb<'a> {
pub fn get_import_source(&self, id: &str) -> Result<ImportSource> {
self.find_one(ImportSourceIden::Id, id)
}
pub fn list_import_sources(&self, workspace_id: &str) -> Result<Vec<ImportSource>> {
self.find_many(ImportSourceIden::WorkspaceId, workspace_id, None)
}
pub fn list_import_sources_by_origin(&self, origin: &str) -> Result<Vec<ImportSource>> {
self.find_many(ImportSourceIden::Origin, origin, None)
}
pub fn find_import_source(
&self,
workspace_id: &str,
importer: &str,
origin: &str,
) -> Result<Option<ImportSource>> {
let sources = self.list_import_sources(workspace_id)?;
Ok(sources.into_iter().find(|s| s.importer == importer && s.origin == origin))
}
pub fn upsert_import_source(
&self,
import_source: &ImportSource,
source: &UpdateSource,
) -> Result<ImportSource> {
self.upsert(import_source, source)
}
pub fn delete_import_source(
&self,
import_source: &ImportSource,
source: &UpdateSource,
) -> Result<ImportSource> {
self.delete_import_source_resources(&import_source.id)?;
self.delete(import_source, source)
}
}
+2
View File
@@ -11,6 +11,8 @@ mod grpc_requests;
mod http_requests; mod http_requests;
mod http_response_events; mod http_response_events;
mod http_responses; mod http_responses;
mod import_source_resources;
mod import_sources;
mod key_values; mod key_values;
mod model_changes; mod model_changes;
mod plugin_key_values; mod plugin_key_values;
@@ -104,7 +104,7 @@ mod tests {
#[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(); let db = query_manager.connect().unwrap();
let workspace = db let workspace = db
.upsert_workspace( .upsert_workspace(
@@ -146,7 +146,7 @@ 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");
let db = query_manager.connect(); let db = query_manager.connect().unwrap();
db.upsert_workspace( db.upsert_workspace(
&Workspace { &Workspace {
@@ -179,7 +179,7 @@ mod tests {
#[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");
let db = query_manager.connect(); let db = query_manager.connect().unwrap();
let workspace = db let workspace = db
.upsert_workspace( .upsert_workspace(
@@ -213,7 +213,7 @@ 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");
let db = query_manager.connect(); let db = query_manager.connect().unwrap();
db.upsert_workspace( db.upsert_workspace(
&Workspace { &Workspace {
@@ -245,7 +245,7 @@ mod tests {
#[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");
let db = query_manager.connect(); let db = query_manager.connect().unwrap();
let payload = json!({ let payload = json!({
"model": { "model": {
+9 -4
View File
@@ -6,8 +6,9 @@ use crate::models::{
AnyModel, CookieJar, CookieJarIden, Environment, EnvironmentIden, Folder, FolderIden, AnyModel, CookieJar, CookieJarIden, Environment, EnvironmentIden, Folder, FolderIden,
GraphQlIntrospection, GraphQlIntrospectionIden, GrpcConnection, GrpcConnectionIden, GrpcEvent, GraphQlIntrospection, GraphQlIntrospectionIden, GrpcConnection, GrpcConnectionIden, GrpcEvent,
GrpcEventIden, GrpcRequest, GrpcRequestIden, HttpRequest, HttpRequestHeader, HttpRequestIden, GrpcEventIden, GrpcRequest, GrpcRequestIden, HttpRequest, HttpRequestHeader, HttpRequestIden,
HttpResponse, HttpResponseEvent, HttpResponseEventIden, HttpResponseIden, HttpResponse, HttpResponseEvent, HttpResponseEventIden, HttpResponseIden, ImportSource,
ResolvedHttpRequestSettings, ResolvedSetting, SyncState, SyncStateIden, WebsocketConnection, ImportSourceIden, ResolvedHttpRequestSettings, ResolvedSetting, SyncState, SyncStateIden,
WebsocketConnection,
WebsocketConnectionIden, WebsocketEvent, WebsocketEventIden, WebsocketRequest, WebsocketConnectionIden, WebsocketEvent, WebsocketEventIden, WebsocketRequest,
WebsocketRequestIden, Workspace, WorkspaceIden, WorkspaceMeta, WorkspaceMetaIden, WebsocketRequestIden, Workspace, WorkspaceIden, WorkspaceMeta, WorkspaceMetaIden,
}; };
@@ -85,6 +86,10 @@ impl<'a> ClientDb<'a> {
self.delete_many_untracked::<Folder>(FolderIden::WorkspaceId, wid)?; self.delete_many_untracked::<Folder>(FolderIden::WorkspaceId, wid)?;
self.delete_many_untracked::<Environment>(EnvironmentIden::WorkspaceId, wid)?; self.delete_many_untracked::<Environment>(EnvironmentIden::WorkspaceId, wid)?;
self.delete_many_untracked::<CookieJar>(CookieJarIden::WorkspaceId, wid)?; self.delete_many_untracked::<CookieJar>(CookieJarIden::WorkspaceId, wid)?;
for import_source in self.list_import_sources(wid)? {
self.delete_import_source_resources(&import_source.id)?;
}
self.delete_many_untracked::<ImportSource>(ImportSourceIden::WorkspaceId, wid)?;
self.delete_many_untracked::<SyncState>(SyncStateIden::WorkspaceId, wid)?; self.delete_many_untracked::<SyncState>(SyncStateIden::WorkspaceId, wid)?;
self.delete_many_untracked::<WorkspaceMeta>(WorkspaceMetaIden::WorkspaceId, wid)?; self.delete_many_untracked::<WorkspaceMeta>(WorkspaceMetaIden::WorkspaceId, wid)?;
self.delete(workspace, source) self.delete(workspace, source)
@@ -104,7 +109,7 @@ impl<'a> ClientDb<'a> {
// Best-effort cleanup of response bodies (disk files and blob chunks). // Best-effort cleanup of response bodies (disk files and blob chunks).
// Failures only orphan unreferenced data, and are logged. // Failures only orphan unreferenced data, and are logged.
let blob_ctx = blobs.connect(); let blob_ctx = blobs.connect()?;
for m in responses { for m in responses {
if let Some(p) = m.body_path { if let Some(p) = m.body_path {
if let Err(e) = std::fs::remove_file(&p) { if let Err(e) = std::fs::remove_file(&p) {
@@ -210,7 +215,7 @@ mod tests {
#[test] #[test]
fn bootstraps_first_workspace_with_real_defaults() { fn bootstraps_first_workspace_with_real_defaults() {
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 db = query_manager.connect().unwrap();
let workspaces = db.list_workspaces().expect("Failed to list workspaces"); let workspaces = db.list_workspaces().expect("Failed to list workspaces");
let workspace = workspaces.first().expect("No workspace was bootstrapped"); let workspace = workspaces.first().expect("No workspace was bootstrapped");
+104 -17
View File
@@ -19,22 +19,10 @@ impl QueryManager {
QueryManager { pool, events_tx } QueryManager { pool, events_tx }
} }
pub fn connect(&self) -> ClientDb<'_> { pub fn connect(&self) -> crate::error::Result<ClientDb<'_>> {
let conn = self.pool.get().expect("Failed to get a new DB connection from the pool"); let conn = crate::pool::acquire(&self.pool, "model")?;
let ctx = DbContext::new(ConnectionOrTx::Connection(conn)); let ctx = DbContext::new(ConnectionOrTx::Connection(conn));
ClientDb::new(ctx, self.events_tx.clone()) Ok(ClientDb::new(ctx, self.events_tx.clone()))
}
pub fn with_conn<F, T>(&self, func: F) -> T
where
F: FnOnce(&ClientDb) -> T,
{
let conn = self.pool.get().expect("Failed to get new DB connection from the pool");
let ctx = DbContext::new(ConnectionOrTx::Connection(conn));
let db = ClientDb::new(ctx, self.events_tx.clone());
func(&db)
} }
pub fn with_tx<T, E>( pub fn with_tx<T, E>(
@@ -44,11 +32,11 @@ impl QueryManager {
where where
E: From<crate::error::Error>, E: From<crate::error::Error>,
{ {
let conn = self.pool.get().expect("Failed to get new DB connection from the pool"); let conn = crate::pool::acquire(&self.pool, "model")?;
// `new_unchecked` takes `&Connection`; see yaak_database::pool for why // `new_unchecked` takes `&Connection`; see yaak_database::pool for why
// the pool never hands out `&mut`. // the pool never hands out `&mut`.
let tx = Transaction::new_unchecked(&conn, TransactionBehavior::Immediate) let tx = Transaction::new_unchecked(&conn, TransactionBehavior::Immediate)
.expect("Failed to start DB transaction"); .map_err(|e| GenericError(format!("Failed to start DB transaction: {e:?}")))?;
let ctx = DbContext::new(ConnectionOrTx::Transaction(&tx)); let ctx = DbContext::new(ConnectionOrTx::Transaction(&tx));
let db = ClientDb::new(ctx, self.events_tx.clone()); let db = ClientDb::new(ctx, self.events_tx.clone());
@@ -67,3 +55,102 @@ impl QueryManager {
} }
} }
} }
#[cfg(test)]
mod tests {
use super::*;
use crate::error::Error;
use crate::migrate::migrate_db;
use crate::models::Workspace;
use crate::util::UpdateSource;
use r2d2_sqlite::SqliteConnectionManager;
use std::time::Duration;
/// A one-connection pool that gives up quickly, so exhaustion is reachable in a test
/// without waiting out the app's acquire timeout.
fn one_connection_pool(
dir: &std::path::Path,
) -> (QueryManager, mpsc::Receiver<ModelPayload>) {
let manager = SqliteConnectionManager::file(dir.join("db.sqlite"));
let pool = r2d2::Pool::builder()
.max_size(1)
.connection_timeout(Duration::from_millis(100))
.build(manager)
.expect("build pool");
migrate_db(&pool).expect("migrate");
let (tx, rx) = mpsc::channel();
(QueryManager::new(pool, tx), rx)
}
fn workspace(name: &str) -> Workspace {
Workspace { name: name.to_string(), ..Default::default() }
}
#[test]
fn exhausted_pool_reports_an_error_instead_of_panicking() {
let dir = tempfile::tempdir().expect("tempdir");
let (qm, _events) = one_connection_pool(dir.path());
let held = qm.connect().expect("first connection");
match qm.connect() {
Ok(_) => panic!("pool should be exhausted"),
Err(e) => {
// The state of the pool rides along, so a report says which failure it was
assert!(
matches!(e, Error::PoolTimeout { connections: 1, idle: 0, .. }),
"got {e:?}"
);
}
}
let err = qm
.with_tx::<(), Error>(|db| {
db.upsert_workspace(&workspace("never runs"), &UpdateSource::Background)?;
Ok(())
})
.expect_err("pool is exhausted");
assert!(matches!(err, Error::PoolTimeout { .. }), "got {err:?}");
drop(held);
qm.connect().expect("pool recovers once the connection is back");
}
#[test]
fn with_tx_returns_its_connection_on_every_exit() {
let dir = tempfile::tempdir().expect("tempdir");
let (qm, _events) = one_connection_pool(dir.path());
qm.with_tx::<(), Error>(|db| {
db.upsert_workspace(&workspace("committed"), &UpdateSource::Background)?;
Ok(())
})
.expect("commit");
let rolled_back = qm.with_tx::<(), Error>(|db| {
db.upsert_workspace(&workspace("rolled back"), &UpdateSource::Background)?;
Err(Error::Unknown)
});
assert!(rolled_back.is_err());
let panicked = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
qm.with_tx::<(), Error>(|db| {
db.upsert_workspace(&workspace("panicked"), &UpdateSource::Background)?;
panic!("closure blew up");
})
}));
assert!(panicked.is_err());
// The pool holds exactly one connection, so this only succeeds if all three
// transactions above gave theirs back.
let names = qm
.connect()
.expect("connection is back in the pool")
.list_workspaces()
.expect("list")
.into_iter()
.map(|w| w.name)
.collect::<Vec<_>>();
assert_eq!(names, vec!["committed".to_string()]);
}
}
+176
View File
@@ -85,6 +85,182 @@ pub struct BatchUpsertResult {
pub websocket_requests: Vec<WebsocketRequest>, pub websocket_requests: Vec<WebsocketRequest>,
} }
/// Where a staged import will be committed.
///
/// The destination workspace and optional folder IDs are captured in the plan so the preview describes
/// the exact destination that confirmation will use.
#[derive(Debug, Clone, Deserialize, Serialize, TS)]
#[serde(rename_all = "snake_case", tag = "type")]
#[ts(export, export_to = "gen_util.ts")]
pub enum ImportDestination {
NewWorkspace,
ExistingWorkspace {
#[serde(rename = "workspaceId")]
workspace_id: String,
#[serde(rename = "folderId")]
#[ts(optional)]
folder_id: Option<String>,
},
}
#[derive(Debug, Clone, Deserialize, Serialize, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export, export_to = "gen_util.ts")]
pub struct ImportPlanWarning {
pub title: String,
pub detail: String,
#[serde(default)]
pub level: ImportPlanWarningLevel,
}
/// Whether a plan's note is something to know or something to think twice about.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize, TS)]
#[serde(rename_all = "snake_case")]
#[ts(export, export_to = "gen_util.ts")]
pub enum ImportPlanWarningLevel {
#[default]
Info,
Warning,
}
impl ImportPlanWarning {
pub fn info(title: impl Into<String>, detail: impl Into<String>) -> Self {
Self {
title: title.into(),
detail: detail.into(),
level: ImportPlanWarningLevel::Info,
}
}
pub fn warning(title: impl Into<String>, detail: impl Into<String>) -> Self {
Self {
title: title.into(),
detail: detail.into(),
level: ImportPlanWarningLevel::Warning,
}
}
}
/// Where an import's contents came from, used to link the committed workspace back to it.
#[derive(Debug, Clone, Deserialize, Serialize, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export, export_to = "gen_util.ts")]
pub struct ImportOrigin {
/// The absolute file path or URL the contents were read from.
pub origin: String,
pub label: String,
}
/// The model types an import plan can contain.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, TS)]
#[serde(rename_all = "snake_case")]
#[ts(export, export_to = "gen_util.ts")]
pub enum ImportResourceType {
Environment,
Folder,
GrpcRequest,
HttpRequest,
WebsocketRequest,
Workspace,
}
impl ImportResourceType {
pub fn as_str(&self) -> &'static str {
match self {
ImportResourceType::Environment => "environment",
ImportResourceType::Folder => "folder",
ImportResourceType::GrpcRequest => "grpc_request",
ImportResourceType::HttpRequest => "http_request",
ImportResourceType::WebsocketRequest => "websocket_request",
ImportResourceType::Workspace => "workspace",
}
}
pub fn from_str(value: &str) -> Option<Self> {
match value {
"environment" => Some(ImportResourceType::Environment),
"folder" => Some(ImportResourceType::Folder),
"grpc_request" => Some(ImportResourceType::GrpcRequest),
"http_request" => Some(ImportResourceType::HttpRequest),
"websocket_request" => Some(ImportResourceType::WebsocketRequest),
"workspace" => Some(ImportResourceType::Workspace),
_ => None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, TS)]
#[serde(rename_all = "snake_case")]
#[ts(export, export_to = "gen_util.ts")]
pub enum ImportPlanAction {
Create,
Update,
Delete,
Unchanged,
KeepLocal,
Conflict,
/// Present in the source but previously turned down; selecting it imports it again
Ignored,
}
/// Extra context for an action that would otherwise be indistinguishable from its plain form.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, TS)]
#[serde(rename_all = "snake_case")]
#[ts(export, export_to = "gen_util.ts")]
pub enum ImportPlanReason {
MovedIntoIgnoredFolder,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, TS)]
#[serde(rename_all = "snake_case")]
#[ts(export, export_to = "gen_util.ts")]
pub enum ImportConflictResolution {
KeepMine,
TakeSource,
}
#[derive(Debug, Clone, Deserialize, Serialize, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export, export_to = "gen_util.ts")]
pub struct ImportPlanItem {
pub action: ImportPlanAction,
pub model: ImportResourceType,
pub model_id: String,
pub name: String,
/// Planned parent folder ID for incoming resources; current parent for deletions.
#[ts(optional)]
pub parent_id: Option<String>,
pub selected: bool,
#[ts(optional)]
pub resolution: Option<ImportConflictResolution>,
#[ts(optional)]
pub reason: Option<ImportPlanReason>,
/// Fields where the source and the local copy disagree, so the preview can say why
#[serde(default)]
pub changed_fields: Vec<String>,
}
#[derive(Debug, Deserialize, Serialize, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export, export_to = "gen_util.ts")]
pub struct ImportPlan {
pub importer: String,
pub destination: ImportDestination,
pub resources: BatchUpsertResult,
pub warnings: Vec<ImportPlanWarning>,
/// Stable source key for every model in `resources`, keyed by its planned ID.
pub source_keys: BTreeMap<String, String>,
/// One entry per plannable resource; commit applies only the selected ones.
#[serde(default)]
pub items: Vec<ImportPlanItem>,
#[serde(default)]
#[ts(optional)]
pub origin: Option<ImportOrigin>,
}
pub fn get_workspace_export_resources( pub fn get_workspace_export_resources(
db: &ClientDb, db: &ClientDb,
yaak_version: &str, yaak_version: &str,
+12 -1
View File
@@ -474,7 +474,18 @@ export type ImportRequest = { content: string, };
export type ImportResources = { workspaces: Array<Workspace>, environments: Array<Environment>, folders: Array<Folder>, httpRequests: Array<HttpRequest>, grpcRequests: Array<GrpcRequest>, websocketRequests: Array<WebsocketRequest>, }; export type ImportResources = { workspaces: Array<Workspace>, environments: Array<Environment>, folders: Array<Folder>, httpRequests: Array<HttpRequest>, grpcRequests: Array<GrpcRequest>, websocketRequests: Array<WebsocketRequest>, };
export type ImportResponse = { resources: ImportResources, }; export type ImportResponse = {
/**
* Display name of the importer that recognized the input.
*/
importer: string, resources: ImportResources,
/**
* Identifies the same source element across re-parses, keyed by the IDs in `resources`.
*
* Must come from the document, never from anything the user can rename in Yaak. Only set
* for formats that carry their own identifiers; the host derives the rest.
*/
sourceKeys?: { [key in string]?: string }, };
export type InternalEvent = { id: string, pluginRefId: string, pluginName: string, replyId: string | null, context: PluginContext, payload: InternalEventPayload, }; export type InternalEvent = { id: string, pluginRefId: string, pluginName: string, replyId: string | null, context: PluginContext, payload: InternalEventPayload, };
+13
View File
@@ -11,6 +11,7 @@ export type AnyModel =
| HttpRequest | HttpRequest
| HttpResponse | HttpResponse
| HttpResponseEvent | HttpResponseEvent
| ImportSource
| KeyValue | KeyValue
| Plugin | Plugin
| Settings | Settings
@@ -318,6 +319,18 @@ export type HttpUrlParameter = {
export type HttpVersion = "auto" | "http1" | "http2"; export type HttpVersion = "auto" | "http1" | "http2";
export type ImportSource = {
model: "import_source";
id: string;
createdAt: string;
updatedAt: string;
workspaceId: string;
importer: string;
origin: string;
originLabel: string;
lastImportedAt: 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 };
+10 -1
View File
@@ -1,5 +1,5 @@
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::collections::HashMap; use std::collections::{BTreeMap, HashMap};
use ts_rs::TS; use ts_rs::TS;
use yaak_models::models::{ use yaak_models::models::{
AnyModel, Environment, Folder, GrpcRequest, HttpRequest, HttpResponse, WebsocketRequest, AnyModel, Environment, Folder, GrpcRequest, HttpRequest, HttpResponse, WebsocketRequest,
@@ -247,7 +247,16 @@ pub struct ImportRequest {
#[serde(default, rename_all = "camelCase")] #[serde(default, rename_all = "camelCase")]
#[ts(export, export_to = "gen_events.ts")] #[ts(export, export_to = "gen_events.ts")]
pub struct ImportResponse { pub struct ImportResponse {
/// Display name of the importer that recognized the input.
pub importer: String,
pub resources: ImportResources, pub resources: ImportResources,
/// Identifies the same source element across re-parses, keyed by the IDs in `resources`.
///
/// Must come from the document, never from anything the user can rename in Yaak. Only set
/// for formats that carry their own identifiers; the host derives the rest.
#[ts(optional)]
pub source_keys: Option<BTreeMap<String, String>>,
} }
#[derive(Debug, Clone, Default, Serialize, Deserialize, TS)] #[derive(Debug, Clone, Default, Serialize, Deserialize, TS)]
Loaded 100 of 141 files, more files were not shown because too many files have changed in this diff. Show more