mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-29 03:24:54 +00:00
feat(plugin): let plugins create, list and delete automations (#65747)
This commit is contained in:
parent
7edab789f7
commit
26f4041911
12 changed files with 207 additions and 78 deletions
|
|
@ -56,7 +56,7 @@ import { KVTable } from "./kv/sql.js"
|
|||
import { Location } from "./location.js"
|
||||
import { LocationServiceMap } from "./location-service-map.js"
|
||||
import { Permission } from "./permission.js"
|
||||
import { Plugin } from "./plugin.js"
|
||||
import { Plugin } from "./plugin/service.js"
|
||||
import { Project } from "./project.js"
|
||||
import { Session } from "./session.js"
|
||||
import { SessionExecution } from "./session/execution.js"
|
||||
|
|
@ -93,6 +93,8 @@ export class DisabledError extends Schema.TaggedError<DisabledError>()("Automati
|
|||
export interface ListInput {
|
||||
readonly sessionID?: SessionSchema.ID
|
||||
readonly projectID?: ProjectID
|
||||
/** Only automations in the project that owns this absolute directory, or that ran in it. */
|
||||
readonly directory?: string
|
||||
}
|
||||
|
||||
export interface Interface {
|
||||
|
|
@ -100,11 +102,13 @@ export interface Interface {
|
|||
input: CreateInput,
|
||||
invocation?: Invocation,
|
||||
) => Effect.Effect<Info, InvalidError | DisabledError | Session.NotFoundError | Permission.Error>
|
||||
readonly list: (input?: ListInput) => Effect.Effect<Info[]>
|
||||
readonly get: (id: ID) => Effect.Effect<Info, NotFoundError>
|
||||
readonly pause: (id: ID) => Effect.Effect<Info, NotFoundError>
|
||||
readonly resume: (id: ID) => Effect.Effect<Info, NotFoundError>
|
||||
readonly remove: (id: ID) => Effect.Effect<void, NotFoundError>
|
||||
/** Oldest first, leaving out automations whose directory has automations off. */
|
||||
readonly list: (input?: ListInput) => Effect.Effect<Info[], InvalidError | DisabledError | Session.NotFoundError>
|
||||
/** These fail with DisabledError when the automation's directory has automations off. */
|
||||
readonly get: (id: ID) => Effect.Effect<Info, NotFoundError | DisabledError>
|
||||
readonly pause: (id: ID) => Effect.Effect<Info, NotFoundError | DisabledError>
|
||||
readonly resume: (id: ID) => Effect.Effect<Info, NotFoundError | DisabledError>
|
||||
readonly remove: (id: ID) => Effect.Effect<void, NotFoundError | DisabledError>
|
||||
/** Whether automations are enabled in the config of `directory`. */
|
||||
readonly enabled: (directory: string) => Effect.Effect<boolean, FileSystem.DirectoryNotFoundError>
|
||||
/** Runs every automation that is due now, at most once each. */
|
||||
|
|
@ -305,6 +309,21 @@ const layer = Layer.effect(
|
|||
}
|
||||
}).pipe(inDirectory(directory))
|
||||
|
||||
// An automation whose folder is gone stays manageable, so it can be inspected and deleted.
|
||||
const visible = (directory: string) =>
|
||||
settings(directory).pipe(
|
||||
Effect.map((value) => value.enabled),
|
||||
Effect.catchTag("FileSystem.DirectoryNotFoundError", () => Effect.succeed(true)),
|
||||
)
|
||||
|
||||
/** The row of an automation callers may manage: it exists and its directory has automations on. */
|
||||
const findVisible = (id: ID) =>
|
||||
Effect.gen(function* () {
|
||||
const row = yield* find(id)
|
||||
if (!(yield* visible(row.directory))) return yield* new DisabledError()
|
||||
return row
|
||||
})
|
||||
|
||||
const find = (id: ID) =>
|
||||
db
|
||||
.select()
|
||||
|
|
@ -1162,6 +1181,19 @@ const layer = Layer.effect(
|
|||
return toInfo(row)
|
||||
}),
|
||||
list: Effect.fn("Automation.list")(function* (input) {
|
||||
if (input?.sessionID !== undefined) {
|
||||
const session = yield* sessions.get(input.sessionID)
|
||||
if (!(yield* visible(session.location.directory))) return yield* new DisabledError()
|
||||
}
|
||||
const directory = input?.directory
|
||||
if (directory !== undefined && !path.isAbsolute(directory))
|
||||
return yield* new InvalidError({ reason: `Directory must be an absolute path: ${directory}` })
|
||||
if (directory !== undefined && !(yield* visible(directory))) return yield* new DisabledError()
|
||||
// Reading ownership must not record a Project for a folder that was only asked about.
|
||||
const owner =
|
||||
directory === undefined
|
||||
? undefined
|
||||
: (yield* projects.resolve(AbsolutePath.make(directory), { persist: false })).id
|
||||
const rows = yield* db
|
||||
.select()
|
||||
.from(AutomationTable)
|
||||
|
|
@ -1174,13 +1206,20 @@ const layer = Layer.effect(
|
|||
.orderBy(asc(AutomationTable.time_created), asc(AutomationTable.id))
|
||||
.all()
|
||||
.pipe(Effect.orDie)
|
||||
return rows.map(toInfo)
|
||||
// A deleted folder may no longer resolve to its Project, so also match automations that ran there.
|
||||
const matching = rows.filter(
|
||||
(row) => directory === undefined || row.project_id === owner || row.directory === directory,
|
||||
)
|
||||
const shown = new Set(
|
||||
yield* Effect.filter(new Set(matching.map((row) => row.directory)), (item) => visible(item)),
|
||||
)
|
||||
return matching.filter((row) => shown.has(row.directory)).map(toInfo)
|
||||
}),
|
||||
get: Effect.fn("Automation.get")(function* (id) {
|
||||
return toInfo(yield* find(id))
|
||||
return toInfo(yield* findVisible(id))
|
||||
}),
|
||||
pause: Effect.fn("Automation.pause")(function* (id) {
|
||||
const row = yield* find(id)
|
||||
const row = yield* findVisible(id)
|
||||
if (row.status !== "active") return toInfo(row)
|
||||
yield* db
|
||||
.update(AutomationTable)
|
||||
|
|
@ -1192,7 +1231,7 @@ const layer = Layer.effect(
|
|||
return toInfo(yield* find(id))
|
||||
}),
|
||||
resume: Effect.fn("Automation.resume")(function* (id) {
|
||||
const row = yield* find(id)
|
||||
const row = yield* findVisible(id)
|
||||
if (row.status !== "paused") return toInfo(row)
|
||||
const now = yield* Clock.currentTimeMillis
|
||||
// An `at` that fell due while paused runs once, late, unless it has expired; a repeating automation resumes at
|
||||
|
|
@ -1216,7 +1255,7 @@ const layer = Layer.effect(
|
|||
return toInfo(yield* find(id))
|
||||
}),
|
||||
remove: Effect.fn("Automation.remove")(function* (id) {
|
||||
yield* find(id)
|
||||
yield* findVisible(id)
|
||||
yield* db.delete(AutomationTable).where(eq(AutomationTable.id, id)).run().pipe(Effect.orDie)
|
||||
yield* FiberMap.remove(watches, id)
|
||||
}),
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ import { Array, Effect, Option, Result, Schema } from "effect"
|
|||
import { Agent } from "../agent.js"
|
||||
import { CodeModeTool } from "../codemode/tool.js"
|
||||
import { Permission } from "../permission.js"
|
||||
import { Plugin } from "../plugin.js"
|
||||
import { Plugin } from "../plugin/service.js"
|
||||
import type { SessionMessage } from "../session/message.js"
|
||||
import type { SessionSchema } from "../session/schema.js"
|
||||
import { Tool } from "../tool.js"
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ import { Agent } from "../agent.js"
|
|||
import { Environment } from "../environment/index.js"
|
||||
import { FileAccess } from "../file-access.js"
|
||||
import { Permission } from "../permission.js"
|
||||
import { Plugin } from "../plugin.js"
|
||||
import { Plugin } from "../plugin/service.js"
|
||||
import type { SessionSchema } from "../session/schema.js"
|
||||
import { Shell } from "../shell.js"
|
||||
import { ShellPermissions } from "../shell/permissions.js"
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@ import { Effect, Schema, Stream } from "effect"
|
|||
import { Agent } from "../agent.js"
|
||||
import { Artifact } from "../artifact.js"
|
||||
import { AISDK } from "../aisdk.js"
|
||||
import { Automation } from "../automation.js"
|
||||
import { Command } from "../command.js"
|
||||
import { Credential } from "../credential.js"
|
||||
import { Bus } from "../bus.js"
|
||||
|
|
@ -54,6 +55,7 @@ export const make = Effect.fn("PluginHost.make")(function* (plugin: Pick<Interfa
|
|||
const app = yield* App.Service
|
||||
const agents = yield* Agent.Service
|
||||
const artifacts = yield* Artifact.Service
|
||||
const automations = yield* Automation.Service
|
||||
const aisdk = yield* AISDK.Service
|
||||
const providers = yield* Provider.Service
|
||||
const models = yield* Model.Service
|
||||
|
|
@ -317,6 +319,12 @@ export const make = Effect.fn("PluginHost.make")(function* (plugin: Pick<Interfa
|
|||
})
|
||||
}),
|
||||
},
|
||||
automation: {
|
||||
// A plugin has no UI listener to answer an interactive ask, so asks settle unattended, as they do over HTTP.
|
||||
create: (input) => automations.create(input).pipe(Effect.provideService(Permission.Unattended, [])),
|
||||
list: (input) => automations.list(input),
|
||||
delete: (input) => automations.remove(input.automationID),
|
||||
},
|
||||
},
|
||||
generate: {
|
||||
text: generateText,
|
||||
|
|
@ -635,6 +643,7 @@ export const requirements = LayerNode.group([
|
|||
Agent.node,
|
||||
Artifact.node,
|
||||
AISDK.node,
|
||||
Automation.node,
|
||||
Provider.node,
|
||||
Model.node,
|
||||
Command.node,
|
||||
|
|
|
|||
|
|
@ -401,7 +401,9 @@ describe("Automation", () => {
|
|||
expect((yield* automations.list({ projectID: (yield* creator).projectID })).map((item) => item.id)).toEqual([
|
||||
automation.id,
|
||||
])
|
||||
expect((yield* automations.list({ sessionID: otherID })).map((item) => item.id)).toEqual([])
|
||||
expect(yield* Effect.flip(automations.list({ sessionID: otherID }))).toMatchObject({
|
||||
_tag: "Session.NotFoundError",
|
||||
})
|
||||
|
||||
expect((yield* automations.pause(automation.id)).status).toBe("paused")
|
||||
yield* TestClock.adjust("150 seconds")
|
||||
|
|
@ -877,6 +879,36 @@ describe("Automation", () => {
|
|||
}),
|
||||
)
|
||||
|
||||
it.effect("hides and refuses automations while their location has automations off", () =>
|
||||
Effect.gen(function* () {
|
||||
const automations = yield* setup(toggleDirectory)
|
||||
toggle.on = true
|
||||
const { id } = yield* automations.create({
|
||||
sessionID,
|
||||
name: "poll",
|
||||
trigger: every("1 minute"),
|
||||
action: prompt("poll"),
|
||||
})
|
||||
expect((yield* automations.list({ directory: toggleDirectory })).map((item) => item.id)).toEqual([id])
|
||||
expect(yield* Effect.flip(automations.list({ directory: "relative" }))).toMatchObject({
|
||||
_tag: "Automation.InvalidError",
|
||||
})
|
||||
|
||||
toggle.on = false
|
||||
expect(yield* automations.list()).toEqual([])
|
||||
expect(yield* Effect.flip(automations.list({ directory: toggleDirectory }))).toMatchObject({
|
||||
_tag: "Automation.DisabledError",
|
||||
})
|
||||
expect(yield* Effect.flip(automations.list({ sessionID }))).toMatchObject({ _tag: "Automation.DisabledError" })
|
||||
expect(yield* Effect.flip(automations.pause(id))).toMatchObject({ _tag: "Automation.DisabledError" })
|
||||
expect(yield* Effect.flip(automations.remove(id))).toMatchObject({ _tag: "Automation.DisabledError" })
|
||||
|
||||
toggle.on = true
|
||||
yield* automations.remove(id)
|
||||
expect(yield* automations.list()).toEqual([])
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("rechecks hourly while automations are disabled in its location, then catches up when enabled", () =>
|
||||
Effect.gen(function* () {
|
||||
const automations = yield* setup(toggleDirectory)
|
||||
|
|
@ -891,7 +923,13 @@ describe("Automation", () => {
|
|||
const before = toggle.reads
|
||||
yield* TestClock.adjust("1 minute")
|
||||
yield* automations.tick
|
||||
expect(yield* automations.get(id)).toMatchObject({ status: "active", runCount: 0, lastOutcome: "disabled" })
|
||||
// Callers can't read an automation while its location has automations off, so read the row.
|
||||
const { db } = yield* Database.Service
|
||||
expect(
|
||||
yield* db.select().from(AutomationTable).where(eq(AutomationTable.id, id)).get().pipe(Effect.orDie),
|
||||
).toMatchObject({ status: "active", run_count: 0, last_outcome: "disabled" })
|
||||
expect(yield* Effect.flip(automations.get(id))).toMatchObject({ _tag: "Automation.DisabledError" })
|
||||
expect(yield* automations.list()).toEqual([])
|
||||
expect(yield* pendingIDs).toEqual([])
|
||||
const reads = toggle.reads
|
||||
expect(reads).toBeGreaterThan(before)
|
||||
|
|
|
|||
70
packages/core/test/plugin/automation.test.ts
Normal file
70
packages/core/test/plugin/automation.test.ts
Normal file
|
|
@ -0,0 +1,70 @@
|
|||
import { expect } from "bun:test"
|
||||
import { Automation } from "@opencode/core/automation"
|
||||
import { Plugin } from "@opencode/core/plugin"
|
||||
import { PluginHost } from "@opencode/core/plugin/host"
|
||||
import { PluginPromise } from "@opencode/core/plugin/promise"
|
||||
import { Effect } from "effect"
|
||||
import { testEffect } from "../lib/effect"
|
||||
import { PluginTestLayer } from "./fixture"
|
||||
|
||||
const it = testEffect(PluginTestLayer)
|
||||
|
||||
it.live("Effect plugins can create, list and delete automations", () =>
|
||||
Effect.gen(function* () {
|
||||
const plugins = yield* Plugin.Service
|
||||
const automations = yield* Automation.Service
|
||||
const context = yield* PluginHost.make(plugins, "test")
|
||||
const session = yield* context.session.create({ title: "Effect automation target" })
|
||||
|
||||
const created = yield* context.experimental.automation.create({
|
||||
directory: context.location.directory,
|
||||
name: "effect inbox",
|
||||
trigger: { type: "cron", cron: "0 * * * *", tz: "Europe/Madrid" },
|
||||
action: { type: "prompt", prompt: "Clean up the inboxes now.", to: { session: session.id } },
|
||||
})
|
||||
|
||||
expect(created).toMatchObject({
|
||||
name: "effect inbox",
|
||||
status: "active",
|
||||
trigger: { type: "cron", cron: "0 * * * *" },
|
||||
action: { type: "prompt", prompt: "Clean up the inboxes now.", to: { session: session.id } },
|
||||
})
|
||||
const listed = yield* context.experimental.automation.list({ directory: context.location.directory })
|
||||
expect(listed.map((item) => item.id)).toContain(created.id)
|
||||
|
||||
yield* context.experimental.automation.delete({ automationID: created.id })
|
||||
expect((yield* automations.list()).map((item) => item.id)).not.toContain(created.id)
|
||||
}),
|
||||
)
|
||||
|
||||
it.live("Promise plugins can create, list and delete automations", () =>
|
||||
Effect.gen(function* () {
|
||||
const plugins = yield* Plugin.Service
|
||||
const automations = yield* Automation.Service
|
||||
const context = yield* PluginHost.make(plugins, "test")
|
||||
const session = yield* context.session.create({ title: "Promise automation target" })
|
||||
const ids: string[] = []
|
||||
|
||||
yield* PluginPromise.fromPromise({
|
||||
id: "test.automation",
|
||||
async setup(ctx) {
|
||||
const created = await ctx.experimental.automation.create({
|
||||
directory: ctx.location.directory,
|
||||
name: "promise inbox",
|
||||
trigger: { type: "cron", cron: "0 9 * * *" },
|
||||
action: { type: "prompt", prompt: "Check the balance now.", to: { session: session.id } },
|
||||
})
|
||||
ids.push(created.id)
|
||||
expect(created).toMatchObject({ name: "promise inbox", action: { to: { session: session.id } } })
|
||||
expect(
|
||||
(await ctx.experimental.automation.list({ directory: ctx.location.directory })).map((item) => item.id),
|
||||
).toContain(created.id)
|
||||
await ctx.experimental.automation.delete({ automationID: created.id })
|
||||
await expect(ctx.experimental.automation.delete({ automationID: created.id })).rejects.toThrow()
|
||||
},
|
||||
}).effect(context)
|
||||
|
||||
expect(ids).toHaveLength(1)
|
||||
expect((yield* automations.list()).map((item) => item.id)).not.toContain(ids[0])
|
||||
}),
|
||||
)
|
||||
|
|
@ -3,6 +3,7 @@ import { App } from "@opencode/core/app"
|
|||
import { Artifact } from "@opencode/core/artifact"
|
||||
import { BlobStore } from "@opencode/core/blob-store"
|
||||
import { AISDK } from "@opencode/core/aisdk"
|
||||
import { Automation } from "@opencode/core/automation"
|
||||
import { Command } from "@opencode/core/command"
|
||||
import { Config } from "@opencode/core/config"
|
||||
import { Credential } from "@opencode/core/credential"
|
||||
|
|
@ -128,6 +129,7 @@ export const makePluginTestLayer = (
|
|||
Agent.node,
|
||||
Artifact.node,
|
||||
AISDK.node,
|
||||
Automation.node,
|
||||
BlobStore.node,
|
||||
Provider.node,
|
||||
Model.node,
|
||||
|
|
|
|||
|
|
@ -81,6 +81,11 @@ export function host(overrides: Overrides = {}): Plugin.Context {
|
|||
transform: () => Effect.die("unused experimental.artifact.transform"),
|
||||
reload: () => Effect.die("unused experimental.artifact.reload"),
|
||||
},
|
||||
automation: {
|
||||
create: () => Effect.die("unused experimental.automation.create"),
|
||||
list: () => Effect.die("unused experimental.automation.list"),
|
||||
delete: () => Effect.die("unused experimental.automation.delete"),
|
||||
},
|
||||
},
|
||||
generate: overrides.generate ?? {
|
||||
text: () => Effect.die("unused generate.text"),
|
||||
|
|
|
|||
|
|
@ -38,6 +38,8 @@ export interface Context {
|
|||
/** Stateless generation with a model and a prompt: no session, history or tools. Video jobs are server-only for now. */
|
||||
readonly generate: Omit<ExperimentalGenerateApi<unknown>, "video">
|
||||
readonly artifact: ExperimentalArtifactDomain
|
||||
/** Create, list and delete automations. Creation fails while automations are off where they would run. */
|
||||
readonly automation: Pick<ExperimentalApi<unknown>["automation"], "create" | "list" | "delete">
|
||||
}
|
||||
readonly integration: IntegrationDomain
|
||||
readonly mcp: MCPDomain
|
||||
|
|
|
|||
|
|
@ -405,6 +405,11 @@ export function fromPromise(plugin: Plugin) {
|
|||
}),
|
||||
),
|
||||
},
|
||||
automation: {
|
||||
create: adaptApiMethod(ExperimentalEndpoints["automation.create"], host.experimental.automation.create),
|
||||
list: adaptApiMethod(ExperimentalEndpoints["automation.list"], host.experimental.automation.list),
|
||||
delete: adaptApiMethod(ExperimentalEndpoints["automation.delete"], host.experimental.automation.delete),
|
||||
},
|
||||
},
|
||||
generate: {
|
||||
text: adaptApiMethod(GenerateEndpoints["generate.text"], host.generate.text),
|
||||
|
|
|
|||
|
|
@ -38,6 +38,8 @@ export interface Context {
|
|||
/** Stateless generation with a model and a prompt: no session, history or tools. Video jobs are server-only for now. */
|
||||
readonly generate: Omit<ExperimentalGenerateApi, "video">
|
||||
readonly artifact: ExperimentalArtifactDomain
|
||||
/** Create, list and delete automations. Creation fails while automations are off where they would run. */
|
||||
readonly automation: Pick<OpenCodeClient["experimental"]["automation"], "create" | "list" | "delete">
|
||||
}
|
||||
readonly integration: IntegrationDomain
|
||||
readonly mcp: MCPDomain
|
||||
|
|
|
|||
|
|
@ -1,35 +1,14 @@
|
|||
import { Automation } from "@opencode/core/automation"
|
||||
import { Permission } from "@opencode/core/permission"
|
||||
import { Project } from "@opencode/core/project"
|
||||
import { Session } from "@opencode/core/session"
|
||||
import { AbsolutePath } from "@opencode/core/schema"
|
||||
import { AutomationNotFoundError, ForbiddenError, InvalidRequestError } from "@opencode/protocol/errors"
|
||||
import type { CreatePayload, ListQuery } from "@opencode/protocol/groups/automation"
|
||||
import { Effect } from "effect"
|
||||
import path from "node:path"
|
||||
import { HttpApiSchema } from "effect/http-api"
|
||||
import { missingSession } from "./session-error"
|
||||
|
||||
/** `automation.*` in the `server.experimental` group. Every route requires automations to be enabled where it runs. */
|
||||
export const makeAutomation = Effect.gen(function* () {
|
||||
const automations = yield* Automation.Service
|
||||
const sessions = yield* Session.Service
|
||||
const projects = yield* Project.Service
|
||||
|
||||
const enabled = (directory: string) =>
|
||||
automations.enabled(directory).pipe(
|
||||
// An automation whose folder is gone stays manageable, so it can be inspected and deleted.
|
||||
Effect.catchTag("FileSystem.DirectoryNotFoundError", () => Effect.succeed(true)),
|
||||
)
|
||||
const allowed = (directory: string) =>
|
||||
enabled(directory).pipe(Effect.flatMap((on) => (on ? Effect.void : Effect.fail(disabled()))))
|
||||
|
||||
const find = (id: Automation.ID) =>
|
||||
Effect.gen(function* () {
|
||||
const info = yield* automations.get(id).pipe(Effect.mapError(missingAutomation))
|
||||
yield* allowed(info.directory)
|
||||
return info
|
||||
})
|
||||
|
||||
return {
|
||||
create: (payload: CreatePayload) =>
|
||||
|
|
@ -47,53 +26,31 @@ export const makeAutomation = Effect.gen(function* () {
|
|||
}),
|
||||
),
|
||||
list: (query: ListQuery) =>
|
||||
Effect.gen(function* () {
|
||||
const session =
|
||||
query.sessionID === undefined
|
||||
? undefined
|
||||
: yield* sessions.get(query.sessionID).pipe(Effect.mapError(missingSession))
|
||||
if (session !== undefined) yield* allowed(session.location.directory)
|
||||
const directory = query.directory
|
||||
if (directory !== undefined && !path.isAbsolute(directory))
|
||||
return yield* new InvalidRequestError({
|
||||
message: `Directory must be an absolute path: ${directory}`,
|
||||
kind: "automation",
|
||||
})
|
||||
if (directory !== undefined) yield* allowed(directory)
|
||||
// Reading ownership must not record a Project for a folder that was only asked about.
|
||||
const projectID =
|
||||
directory === undefined
|
||||
? undefined
|
||||
: (yield* projects.resolve(AbsolutePath.make(directory), { persist: false })).id
|
||||
const rows = yield* automations.list({ sessionID: query.sessionID })
|
||||
// A deleted folder may no longer resolve to its Project, so also match automations that ran there.
|
||||
const matching = rows.filter(
|
||||
(row) => directory === undefined || row.projectID === projectID || row.directory === directory,
|
||||
)
|
||||
// Each automation is shown only where the flag allows it, the same as `get`.
|
||||
const directories = new Set(matching.map((row) => row.directory))
|
||||
const visible = new Set(yield* Effect.filter(directories, enabled))
|
||||
return { data: matching.filter((row) => visible.has(row.directory)) }
|
||||
}),
|
||||
get: (id: Automation.ID) => find(id).pipe(Effect.map((data) => ({ data }))),
|
||||
pause: (id: Automation.ID) =>
|
||||
find(id).pipe(
|
||||
Effect.andThen(automations.pause(id).pipe(Effect.mapError(missingAutomation))),
|
||||
automations.list(query).pipe(
|
||||
Effect.map((data) => ({ data })),
|
||||
Effect.catchTags({
|
||||
"Automation.InvalidError": (error) =>
|
||||
Effect.fail(new InvalidRequestError({ message: error.message, kind: "automation" })),
|
||||
"Automation.DisabledError": () => Effect.fail(disabled()),
|
||||
"Session.NotFoundError": (error) => Effect.fail(missingSession(error)),
|
||||
}),
|
||||
),
|
||||
resume: (id: Automation.ID) =>
|
||||
find(id).pipe(
|
||||
Effect.andThen(automations.resume(id).pipe(Effect.mapError(missingAutomation))),
|
||||
Effect.map((data) => ({ data })),
|
||||
),
|
||||
remove: (id: Automation.ID) =>
|
||||
find(id).pipe(
|
||||
Effect.andThen(automations.remove(id).pipe(Effect.mapError(missingAutomation))),
|
||||
Effect.as(HttpApiSchema.NoContent.make()),
|
||||
),
|
||||
get: (id: Automation.ID) => managed(automations.get(id).pipe(Effect.map((data) => ({ data })))),
|
||||
pause: (id: Automation.ID) => managed(automations.pause(id).pipe(Effect.map((data) => ({ data })))),
|
||||
resume: (id: Automation.ID) => managed(automations.resume(id).pipe(Effect.map((data) => ({ data })))),
|
||||
remove: (id: Automation.ID) => managed(automations.remove(id).pipe(Effect.as(HttpApiSchema.NoContent.make()))),
|
||||
}
|
||||
})
|
||||
|
||||
function managed<A>(effect: Effect.Effect<A, Automation.NotFoundError | Automation.DisabledError>) {
|
||||
return effect.pipe(
|
||||
Effect.catchTags({
|
||||
"Automation.NotFoundError": (error) => Effect.fail(missingAutomation(error)),
|
||||
"Automation.DisabledError": () => Effect.fail(disabled()),
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
function missingAutomation(error: { readonly automationID: Automation.ID }) {
|
||||
return new AutomationNotFoundError({
|
||||
automationID: error.automationID,
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue