Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { useAtomValue } from "@effect/atom-react";
import type { StaticScreenProps } from "@react-navigation/native";
import { issueTrackerSummary } from "@t3tools/client-runtime/state/issue-trackers";
import {
issueTrackerBindable,
issueTrackerSummary,
} from "@t3tools/client-runtime/state/issue-trackers";
import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
import {
AuthSettingsWriteScope,
Expand All @@ -10,8 +13,10 @@ import {
import * as Option from "effect/Option";
import type { ReactNode } from "react";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { View } from "react-native";

import { AppText as Text } from "../../components/ui/AppText";
import { Button } from "../../components/ui/Button";
import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScrollView";
import { useEnvironments } from "../../state/environments";
import { issueTrackerEnvironment } from "../../state/issueTrackers";
Expand Down Expand Up @@ -159,7 +164,6 @@ export function SettingsIssueTrackerRouteScreen({
const canEdit = useAtomValue(issueTrackerEnvironment.connect.permissionAtom(environmentId));
const tracker = query.data?.trackers.find((entry) => entry.tracker === route.params.tracker);
const disabled = !canWrite || !canEdit;
const usable = tracker?.connected === true && tracker.account !== null;
return (
<DetailPage title={tracker?.displayName ?? "Issue tracker"}>
{!environment || !tracker ? (
Expand All @@ -169,14 +173,19 @@ export function SettingsIssueTrackerRouteScreen({
<Text selectable className="px-2 text-sm text-foreground-muted">
{issueTrackerSummary(tracker, query.data?.bindings ?? {})}
</Text>
{tracker.unavailable ? (
<View className="px-2">
<Button label="Try again" tone="secondary" onPress={query.refresh} />
</View>
) : null}
<SettingsSection title={tracker.credential.label}>
<IssueTrackerCredentialForm
environmentId={environmentId}
tracker={tracker}
disabled={disabled}
/>
</SettingsSection>
{usable && tracker.scopes.length > 0 ? (
{issueTrackerBindable(tracker) ? (
<SettingsSection
title="Projects"
footer={`Pick the ${tracker.displayName} ${tracker.scopeNoun} whose issues each project lists beside its repository's own.`}
Expand Down
111 changes: 111 additions & 0 deletions apps/server/src/issue/IssueTrackerConnections.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
import { describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { IssueTrackerKind, ProjectId } from "@t3tools/contracts";
import { IssueTrackerError } from "@t3tools/source-control-core/server/IssueTracker";

import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import * as IssueTrackerBindings from "../persistence/IssueTrackerBindings.ts";
import * as IssueTrackerConnections from "./IssueTrackerConnections.ts";
import * as IssueTrackerRegistry from "./IssueTrackerRegistry.ts";

const linear = IssueTrackerKind.make("linear");
const projectId = ProjectId.make("project-1");

const listWithProbeFailure = (reason: IssueTrackerError["reason"]) =>
Effect.gen(function* () {
const tracker = {
kind: linear,
capabilities: {
create: true,
edit: true,
comment: true,
labels: true,
assignees: true,
reactions: true,
templates: true,
linkedPullRequests: true,
events: true,
search: true,
},
standalone: {
tracker: linear,
displayName: "Linear",
host: "linear.app",
scopeNoun: "team",
credential: { label: "Personal API key", helpUrl: null },
},
getViewer: () => Effect.succeed("wout"),
listIssues: () => Effect.succeed({ items: [], nextCursor: null }),
getIssue: () => Effect.die("unused"),
getComments: () => Effect.succeed({ comments: [], nextCursor: null }),
probeCredential: () =>
Effect.fail(
new IssueTrackerError({
tracker: linear,
operation: "viewer",
reason,
detail:
reason === "rate-limited"
? "Linear's rate limit was reached."
: "Linear could not be reached.",
}),
),
};
return yield* IssueTrackerConnections.IssueTrackerConnections.pipe(
Effect.flatMap((service) => service.list),
Effect.result,
Effect.provide(
IssueTrackerConnections.layer.pipe(
Layer.provide(
Layer.mergeAll(
Layer.succeed(
IssueTrackerRegistry.IssueTrackerRegistry,
IssueTrackerRegistry.fromTrackers([tracker]),
),
Layer.mock(ServerSecretStore.ServerSecretStore)({
get: () => Effect.succeedSome(new TextEncoder().encode("saved-valid-key")),
}),
Layer.mock(IssueTrackerBindings.IssueTrackerBindingsRepository)({
list: Effect.succeed(new Map([[projectId, { tracker: linear, scope: "FAC" }]])),
}),
),
),
),
),
);
});

describe("IssueTrackerConnections", () => {
it.effect.each(["rate-limited", "failed"] as const)(
"lists a %s probe as unavailable, keeping the credential and bound scopes",
(reason) =>
Effect.gen(function* () {
const result = yield* listWithProbeFailure(reason);
expect(result).toMatchObject({
_tag: "Success",
success: {
trackers: [
{
connected: true,
account: null,
unavailable: true,
scopes: [{ key: "FAC", name: "FAC" }],
},
],
bindings: { [projectId]: { tracker: linear, scope: "FAC" } },
},
});
}),
);

it.effect("lists an authentication refusal as a rejected saved credential", () =>
Effect.gen(function* () {
const result = yield* listWithProbeFailure("unauthenticated");
expect(result).toMatchObject({
_tag: "Success",
success: { trackers: [{ connected: true, account: null, unavailable: false, scopes: [] }] },
});
}),
);
});
89 changes: 55 additions & 34 deletions apps/server/src/issue/IssueTrackerConnections.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,10 @@ import {
type IssueTrackerConnection,
type IssueTrackerConnectionList,
} from "@t3tools/contracts";
import type { StandaloneIssueTrackerApi } from "@t3tools/source-control-core/server/IssueTracker";
import type {
IssueTrackerError,
StandaloneIssueTrackerApi,
} from "@t3tools/source-control-core/server/IssueTracker";

import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import * as IssueTrackerBindings from "../persistence/IssueTrackerBindings.ts";
Expand Down Expand Up @@ -76,47 +79,74 @@ const make = Effect.gen(function* () {
connected: false,
account: null,
detail: null,
unavailable: false,
scopes: [],
});

/** The tracker's view of a stored credential; a refusal is status, not a failure. */
const status = (api: StandaloneIssueTrackerApi, token: string) =>
const probeFailure = (error: IssueTrackerError) =>
new IssueTrackerConnectionError({
tracker: error.tracker,
reason: error.reason === "unauthenticated" ? "rejected" : "failed",
detail: IssueService.trackerDetail(error),
cause: error,
});

/** The tracker's view of a stored credential; a refusal or an outage is status, not a failure. */
const status = (
api: StandaloneIssueTrackerApi,
token: string,
bound: IssueTrackerConnectionList["bindings"],
) =>
api.probeCredential(token).pipe(
Effect.map((probe): IssueTrackerConnection => ({
...api.standalone,
connected: true,
account: probe.account,
detail: null,
unavailable: false,
scopes: probe.scopes,
})),
Effect.catch((error) =>
Effect.succeed<IssueTrackerConnection>({
Effect.catch((error) => {
const unavailable = error.reason !== "unauthenticated";
// Scope names come only from the tracker, so bound projects keep their pickers by key.
const boundKeys = new Set(
Object.values(bound).flatMap((binding) =>
binding.tracker === api.kind ? [binding.scope] : [],
),
);
return Effect.succeed<IssueTrackerConnection>({
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
...api.standalone,
connected: true,
account: null,
detail: IssueService.trackerDetail(error),
scopes: [],
}),
),
unavailable,
scopes: unavailable ? [...boundKeys].map((key) => ({ key, name: key })) : [],
});
}),
);

const current = (api: StandaloneIssueTrackerApi) =>
secrets.get(issueTrackerSecretName(api.kind)).pipe(
Effect.mapError(secretFailure(api.kind, "The stored credential could not be read.")),
Effect.flatMap((stored) =>
Option.isNone(stored)
? Effect.succeed(disconnected(api))
: status(api, new TextDecoder().decode(stored.value)),
const current =
(bound: IssueTrackerConnectionList["bindings"]) => (api: StandaloneIssueTrackerApi) =>
secrets.get(issueTrackerSecretName(api.kind)).pipe(
Effect.mapError(secretFailure(api.kind, "The stored credential could not be read.")),
Effect.flatMap((stored) =>
Option.isNone(stored)
? Effect.succeed(disconnected(api))
: status(api, new TextDecoder().decode(stored.value), bound),
),
);

const list: IssueTrackerConnections["Service"]["list"] = Effect.gen(function* () {
const bound = Object.fromEntries(
yield* bindings.list.pipe(
// No single tracker is at fault; the first registered one carries the report.
Effect.mapError(secretFailure(anyTracker, "The project bindings could not be read.")),
),
);

const list: IssueTrackerConnections["Service"]["list"] = Effect.all({
trackers: Effect.forEach(registry.standalone, current, { concurrency: 4 }),
bindings: bindings.list.pipe(
Effect.map((bound) => Object.fromEntries(bound)),
// No single tracker is at fault; the first registered one carries the report.
Effect.mapError(secretFailure(anyTracker, "The project bindings could not be read.")),
),
const trackers = yield* Effect.forEach(registry.standalone, current(bound), {
concurrency: 4,
});
return { trackers, bindings: bound };
});

const disconnect = Effect.fn("IssueTrackerConnections.disconnect")(function* (
Expand All @@ -137,17 +167,7 @@ const make = Effect.gen(function* () {
)(function* (input) {
const api = yield* requireTracker(input.tracker);
if (input.token === null) return yield* disconnect(api);
const probe = yield* api.probeCredential(input.token).pipe(
Effect.mapError(
(error) =>
new IssueTrackerConnectionError({
tracker: input.tracker,
reason: error.reason === "unauthenticated" ? "rejected" : "failed",
detail: IssueService.trackerDetail(error),
cause: error,
}),
),
);
const probe = yield* api.probeCredential(input.token).pipe(Effect.mapError(probeFailure));
yield* secrets
.set(issueTrackerSecretName(api.kind), encoder.encode(input.token))
.pipe(Effect.mapError(secretFailure(api.kind, "The credential could not be stored.")));
Expand All @@ -156,6 +176,7 @@ const make = Effect.gen(function* () {
connected: true,
account: probe.account,
detail: null,
unavailable: false,
scopes: probe.scopes,
};
});
Expand Down
21 changes: 18 additions & 3 deletions apps/web/src/components/settings/IssueTrackerSettings.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import { useAtomValue } from "@effect/atom-react";
import { issueTrackerSummary } from "@t3tools/client-runtime/state/issue-trackers";
import {
issueTrackerBindable,
issueTrackerRejected,
issueTrackerSummary,
} from "@t3tools/client-runtime/state/issue-trackers";
import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
import { ChevronDownIcon, ExternalLinkIcon, XIcon } from "lucide-react";
import { useState, type ElementType } from "react";
Expand Down Expand Up @@ -80,6 +84,8 @@ export function IssueTrackerSettings({ environmentId }: { readonly environmentId
environmentId={environmentId}
tracker={tracker}
bindings={query.data?.bindings ?? {}}
onRetry={query.refresh}
retrying={query.isPending}
/>
))}
</SettingsSection>
Expand All @@ -90,10 +96,14 @@ function TrackerRow({
environmentId,
tracker,
bindings,
onRetry,
retrying,
}: {
readonly environmentId: EnvironmentId;
readonly tracker: IssueTrackerConnection;
readonly bindings: IssueTrackerConnectionList["bindings"];
readonly onRetry: () => void;
readonly retrying: boolean;
}) {
const Icon = TRACKER_ICONS[tracker.tracker];
const canEdit = useAtomValue(issueTrackerEnvironment.connect.permissionAtom(environmentId));
Expand Down Expand Up @@ -139,14 +149,19 @@ function TrackerRow({
<span className="truncate text-sm font-medium text-foreground">
{tracker.displayName}
</span>
{tracker.connected && tracker.account === null ? (
{issueTrackerRejected(tracker) ? (
<Badge variant="destructive" size="sm">
Credential rejected
</Badge>
) : null}
</div>
<p className="text-xs leading-normal text-muted-foreground/80">{summary}</p>
</div>
{tracker.unavailable ? (
<Button size="xs" variant="outline" disabled={retrying} onClick={onRetry}>
Retry
</Button>
) : null}
<Button
size="icon-xs"
variant="ghost-muted"
Expand Down Expand Up @@ -215,7 +230,7 @@ function TrackerRow({
</div>
}
/>
{usable ? (
{issueTrackerBindable(tracker) ? (
<ProjectBindings
environmentId={environmentId}
tracker={tracker}
Expand Down
10 changes: 10 additions & 0 deletions packages/client-runtime/src/state/issueTrackers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,16 @@ export function createIssueTrackerEnvironmentAtoms<R, E>(
* The line under a tracker's name. A connected tracker lists nothing until a project is linked
* to one of its scopes, so the line says how many are, and what to do when none is.
*/
/** The tracker refused the stored credential, as opposed to not being reachable to ask. */
export const issueTrackerRejected = (tracker: IssueTrackerConnection): boolean =>
tracker.connected && tracker.account === null && !tracker.unavailable;

/** Projects can be bound: the credential works, or the tracker is only briefly unreachable. */
export const issueTrackerBindable = (tracker: IssueTrackerConnection): boolean =>
tracker.connected &&
(tracker.account !== null || tracker.unavailable) &&
tracker.scopes.length > 0;

export function issueTrackerSummary(
tracker: IssueTrackerConnection,
bindings: IssueTrackerConnectionList["bindings"],
Expand Down
6 changes: 6 additions & 0 deletions packages/contracts/src/issue.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import * as Schema from "effect/Schema";
import * as Effect from "effect/Effect";
import * as HttpServerRespondable from "effect/http/HttpServerRespondable";
import * as HttpServerResponse from "effect/http/HttpServerResponse";

Expand Down Expand Up @@ -570,6 +571,11 @@ export const IssueTrackerConnection = Schema.Struct({
account: Schema.NullOr(TrimmedNonEmptyString),
/** Why a stored credential did not work, when it did not. */
detail: Schema.NullOr(TrimmedNonEmptyString),
/**
* The tracker could not vet the stored credential just now (rate limit, outage), so it is not
* known to be rejected; `scopes` then holds only the scopes projects are bound to.
*/
unavailable: Schema.Boolean.pipe(Schema.withDecodingDefaultKey(Effect.succeed(false))),
scopes: Schema.Array(IssueTrackerScope),
});
export type IssueTrackerConnection = typeof IssueTrackerConnection.Type;
Expand Down
Loading