diff --git a/.changeset/schedule-scope-by-name.md b/.changeset/schedule-scope-by-name.md new file mode 100644 index 0000000000..288ae8cfac --- /dev/null +++ b/.changeset/schedule-scope-by-name.md @@ -0,0 +1,13 @@ +--- +"@executor-js/sdk": patch +"@executor-js/hosted-server": patch +"@executor-js/local-server": patch +--- + +Schedule configure and run now, by name, find app schedules without a scope. Run now takes an +optional `scope` (`app` or `user`), as configure does; it previously only looked for the caller's +own copy, so an app schedule was not found. Without `scope`, both routes act on the schedule saved +under the name, else on the app's declaration, else on the caller's copy as before. When both the +app schedule and the caller's copy are saved under the name, they fail with +`ScheduleScopeRequired` instead of guessing. Each scope keeps its authorization: only the app's +managers configure or run an app schedule. The SDK adds `schedules.scope`, which resolves it. diff --git a/apps/hosted/server/src/contracts/schedules.ts b/apps/hosted/server/src/contracts/schedules.ts index d8b3380fcc..6dbbf2a602 100644 --- a/apps/hosted/server/src/contracts/schedules.ts +++ b/apps/hosted/server/src/contracts/schedules.ts @@ -1,6 +1,6 @@ /** Organization-aware schedule management, with browser-only human review. */ import { Context, Effect, Schema } from "effect"; -import { HttpApiEndpoint, HttpApiGroup } from "effect/http-api"; +import { HttpApiEndpoint, HttpApiGroup, OpenApi } from "effect/http-api"; import { AccountScope, AppId, @@ -43,13 +43,17 @@ const app = { ...organization, app: AppId }; const copy = { ...app, name: Schema.NonEmptyString, copy: ScheduleId }; const prefix = "/api/organizations/:organization"; const errors = [...ScheduleErrors, OrganizationForbidden, Forbidden] as const; +/** How a by-name route picks between the app schedule and the caller's copy; agents read it. */ +const scopeRule = + "scope \"app\" is the app declaration's one schedule, which runs without a caller with the app's linked accounts; scope \"user\" is the caller's own copy of a user declaration. Without scope, the schedule saved under the name decides; with none saved, the app's declaration; otherwise user. When both the app schedule and the caller's copy are saved under the name, the call fails with ScheduleScopeRequired: retry with scope."; /** * App source owns timing/arguments. These routes only control schedule copies and review runs. * Each member has at most one copy of a user declaration, which runs as that member with the app's * linked accounts and the accounts they linked to it. An app declaration has one schedule, without * an actor, which runs with the app's linked accounts and which only the app's managers control. - * Routes by name act on the caller's own copy, or with `scope: "app"` on the app schedule; routes - * by copy act on one copy, which its member, or someone who manages the app, controls. + * Routes by name act on the caller's own copy, or with `scope: "app"` on the app schedule, and + * without a scope resolve it by name; routes by copy act on one copy, which its member, or someone + * who manages the app, controls. */ export const HostedSchedules = HttpApiGroup.make("schedules") .add( @@ -74,21 +78,29 @@ export const HostedSchedules = HttpApiGroup.make("schedules") approvalMode: Schema.optional(ScheduleApprovalMode), /** * `app` configures an app declaration's one schedule, which runs without a caller with - * the app's linked accounts and only its managers control; `user`, the default, the - * caller's own copy of a user declaration. + * the app's linked accounts and only its managers control; `user`, the caller's own copy + * of a user declaration. Omitted, the scope is resolved by name (see `scopeRule`). */ scope: Schema.optional(AccountScope), }), success: ScheduleSettings, error: errors, - }), + }).annotate( + OpenApi.Description, + `Enable or pause a schedule by name, or set its approval mode. ${scopeRule} Only the app's managers configure an app schedule.`, + ), ) .add( HttpApiEndpoint.post("runNow", `${prefix}/apps/:app/schedules/:name/run`, { params: { ...app, name: Schema.NonEmptyString }, + /** `app` runs the app schedule, `user` the caller's own copy; omitted, see `scopeRule`. */ + query: { scope: Schema.optional(AccountScope) }, success: ScheduleSettings, error: errors, - }), + }).annotate( + OpenApi.Description, + `Start an enabled schedule's run now, by name. ${scopeRule} Only the app's managers run an app schedule.`, + ), ) .add( HttpApiEndpoint.patch("update", `${prefix}/apps/:app/schedules/:name/copies/:copy`, { diff --git a/apps/hosted/server/src/implementation/schedules.ts b/apps/hosted/server/src/implementation/schedules.ts index 272b6e40da..89bbf91739 100644 --- a/apps/hosted/server/src/implementation/schedules.ts +++ b/apps/hosted/server/src/implementation/schedules.ts @@ -126,6 +126,23 @@ const runCopy = (executor: Executor, owner: OwnerId, copy: ScheduleSettings) => yield* wake; return result; }); +/** + * The scope a by-name route acts on when the request names none. Only someone who may read the app, + * and so list its schedules, has it resolved; anyone else keeps the user scope, as before, and the + * route's own checks answer them. + */ +const resolvedScope = ( + executor: Executor, + params: { readonly app: AppId; readonly name: string }, + actor: string, +) => + Effect.gen(function* () { + const owner = yield* appReaderOwner(params.app).pipe( + Effect.catchTag("OrganizationForbidden", () => Effect.succeed(undefined)), + ); + if (owner === undefined) return "user" as const; + return yield* executor.schedules.scope({ ...params, owner, actor }); + }); /** Shared handlers retain product ownership and reuse the existing browser approval contract. */ export const hostedScheduleHandlers = HttpApiBuilder.group(HostedApi, "schedules", (handlers) => handlers @@ -152,7 +169,8 @@ export const hostedScheduleHandlers = HttpApiBuilder.group(HostedApi, "schedules const executor = yield* Effect.flatten(HostedExecutor); const actor = yield* CurrentUserId; if (actor === undefined) return yield* new Forbidden(); - const { scope, ...settings } = payload; + const { scope: requested, ...settings } = payload; + const scope = requested ?? (yield* resolvedScope(executor, params, actor)); if (scope === "app") { // The app schedule runs without a caller, with the app's linked accounts; only the app's // managers enable or pause it. The SDK refuses a declaration of the other scope. @@ -181,11 +199,22 @@ export const hostedScheduleHandlers = HttpApiBuilder.group(HostedApi, "schedules return result; }), ) - .handle("runNow", ({ params }) => + .handle("runNow", ({ params, query }) => Effect.gen(function* () { const executor = yield* Effect.flatten(HostedExecutor); const actor = yield* CurrentUserId; if (actor === undefined) return yield* new Forbidden(); + const scope = query.scope ?? (yield* resolvedScope(executor, params, actor)); + if (scope === "app") { + // As configure: only the app's managers run the app schedule, which has no actor. + const owner = yield* appManagerOwner(params.app); + const copy = yield* executor.schedules.copy({ + app: params.app, + name: params.name, + owner, + }); + return yield* runCopy(executor, owner, copy); + } const owner = yield* currentOwner; yield* usableApp(executor, owner, params.app); // The caller's own copy. diff --git a/apps/hosted/web/src/contracts/errors.ts b/apps/hosted/web/src/contracts/errors.ts index 6cee8a3822..19cfd03509 100644 --- a/apps/hosted/web/src/contracts/errors.ts +++ b/apps/hosted/web/src/contracts/errors.ts @@ -39,6 +39,8 @@ const errorMessage = Match.type().pipe( ScheduleConflict: () => "The schedule is busy or changed. Check its current status and try again.", ScheduleInvalid: () => "Update the interval or calendar timing in the app source.", + ScheduleScopeRequired: () => + "Both the app schedule and your own copy have this name. Choose which one to change.", GroupNotFound: () => "This group is unavailable or you do not have access. Ask an organization admin.", GroupsUnavailable: () => "Groups could not be loaded or saved. Try again.", diff --git a/apps/local/server/src/contracts/schedules.ts b/apps/local/server/src/contracts/schedules.ts index b809c9f6ea..1fb7a5736f 100644 --- a/apps/local/server/src/contracts/schedules.ts +++ b/apps/local/server/src/contracts/schedules.ts @@ -1,6 +1,6 @@ /** Local schedule controls use paired dashboard access and have no hosted organization fields. */ import { Schema } from "effect"; -import { HttpApiEndpoint, HttpApiGroup } from "effect/http-api"; +import { HttpApiEndpoint, HttpApiGroup, OpenApi } from "effect/http-api"; import { AccountScope, AppId, @@ -21,12 +21,16 @@ import { const app = { app: AppId }; const copy = { ...app, name: Schema.NonEmptyString, copy: ScheduleId }; const prefix = "/dashboard/api"; +/** How a by-name route picks between the app schedule and the local copy; agents read it. */ +const scopeRule = + 'scope "app" is the app declaration\'s one schedule, which runs without a caller with the app\'s linked accounts; scope "user" is your own copy of a user declaration. Without scope, the schedule saved under the name decides; with none saved, the app\'s declaration; otherwise user. When both the app schedule and your copy are saved under the name, the call fails with ScheduleScopeRequired: retry with scope.'; /** * DashboardAccess is attached by the containing API to avoid a contract import cycle. User schedules * run as the local subject, which has one copy of each user declaration and runs it with the app's * linked accounts and the accounts linked to it. An app declaration has one schedule, without an * actor, which runs with the app's linked accounts only. Routes by name act on the local subject's - * copy, or with `scope: "app"` on the app schedule; routes by copy act on one copy. + * copy, or with `scope: "app"` on the app schedule, and without a scope resolve it by name; routes + * by copy act on one copy. */ export const DashboardSchedules = HttpApiGroup.make("schedules") .add( @@ -51,20 +55,26 @@ export const DashboardSchedules = HttpApiGroup.make("schedules") approvalMode: Schema.optional(ScheduleApprovalMode), /** * `app` configures an app declaration's one schedule, which runs without a caller with the - * app's linked accounts; `user`, the default, the local subject's copy of a user declaration. + * app's linked accounts; `user`, the local subject's copy of a user declaration. Omitted, + * the scope is resolved by name (see `scopeRule`). */ scope: Schema.optional(AccountScope), }), success: ScheduleSettings, error: ScheduleErrors, - }), + }).annotate( + OpenApi.Description, + `Enable or pause a schedule by name, or set its approval mode. ${scopeRule}`, + ), ) .add( HttpApiEndpoint.post("runNow", `${prefix}/apps/:app/schedules/:name/run`, { params: { ...app, name: Schema.NonEmptyString }, + /** `app` runs the app schedule, `user` the local subject's copy; omitted, see `scopeRule`. */ + query: { scope: Schema.optional(AccountScope) }, success: ScheduleSettings, error: ScheduleErrors, - }), + }).annotate(OpenApi.Description, `Start an enabled schedule's run now, by name. ${scopeRule}`), ) .add( HttpApiEndpoint.patch("update", `${prefix}/apps/:app/schedules/:name/copies/:copy`, { diff --git a/apps/local/server/src/implementation/schedules.ts b/apps/local/server/src/implementation/schedules.ts index 7c0b8941b3..59fd564f0c 100644 --- a/apps/local/server/src/implementation/schedules.ts +++ b/apps/local/server/src/implementation/schedules.ts @@ -32,18 +32,29 @@ export const localScheduleHandlers = ( ), ), ) - // The app schedule has no actor; the SDK refuses a declaration of the other scope. + // The app schedule has no actor; the SDK refuses a declaration of the other scope. Without a + // scope, the saved schedule or else the declaration decides. .handle("configure", ({ params, payload: { scope, ...settings } }) => - executor.schedules.configure({ - ...params, - ...settings, - ...(scope === "app" ? {} : { actor: localActor }), + Effect.gen(function* () { + const resolved = + scope ?? (yield* executor.schedules.scope({ ...params, actor: localActor })); + return yield* executor.schedules.configure({ + ...params, + ...settings, + ...(resolved === "app" ? {} : { actor: localActor }), + }); }), ) - .handle("runNow", ({ params }) => - executor.schedules - .copy({ ...params, actor: localActor }) - .pipe(Effect.flatMap((copy) => executor.schedules.runNow({ ...params, copy: copy.id }))), + .handle("runNow", ({ params, query }) => + Effect.gen(function* () { + const scope = + query.scope ?? (yield* executor.schedules.scope({ ...params, actor: localActor })); + const copy = yield* executor.schedules.copy({ + ...params, + ...(scope === "app" ? {} : { actor: localActor }), + }); + return yield* executor.schedules.runNow({ ...params, copy: copy.id }); + }), ) .handle("update", ({ params, payload }) => executor.schedules.update({ ...params, ...payload }), diff --git a/apps/local/web/src/contracts/errors.ts b/apps/local/web/src/contracts/errors.ts index e4b9f8b8b7..8e56c54909 100644 --- a/apps/local/web/src/contracts/errors.ts +++ b/apps/local/web/src/contracts/errors.ts @@ -73,6 +73,11 @@ const errorMessage = Match.type().pipe( ), ScheduleInvalid: () => message("Invalid schedule", "Update the interval or calendar timing in the app source."), + ScheduleScopeRequired: () => + message( + "Choose a schedule", + "Both the app schedule and your own copy have this name. Choose which one to change.", + ), RegistryError: (error) => message("Public app unavailable", registryErrorMessage(error)), AppAccessDenied: () => message("Action unavailable", "You do not have permission to change this app."), diff --git a/e2e/test-plan.ts b/e2e/test-plan.ts index 4ac22bfd97..541567b60f 100644 --- a/e2e/test-plan.ts +++ b/e2e/test-plan.ts @@ -7183,6 +7183,17 @@ export const scenarios = plan({ cloud: scheduled, }, }, + hostedAppScheduleScope: { + fixtures: "actors", + file: "app-schedules.spec.ts", + title: + "by-name schedule configure and run now without a scope resolve the app schedule or the caller's copy, refuse to guess when both are saved, and keep each scope's authorization", + targets: { + local: na("Hosted managers and members; Local app schedules have their own scenario."), + "self-host": scheduled, + cloud: scheduled, + }, + }, hostedAppScopeWorkflows: { fixtures: "actors", file: "app-schedules.spec.ts", @@ -8503,7 +8514,7 @@ export const scenarios = plan({ localAppScheduleAppLinks: { file: "local-app-account-app-links.spec.ts", title: - "a local app schedule runs with only the app's linked account and waits for one while none is linked", + "a local app schedule runs with only the app's linked account and waits for one while none is linked, and by-name run now and configure without a scope act on it", targets: { local: scheduled, "self-host": na("Local app link routes; hosted app links have their own scenarios."), diff --git a/e2e/tests/app-schedules.spec.ts b/e2e/tests/app-schedules.spec.ts index 3efc54a43a..529484fa0d 100644 --- a/e2e/tests/app-schedules.spec.ts +++ b/e2e/tests/app-schedules.spec.ts @@ -11,6 +11,7 @@ import { Resource } from "../support/contracts.ts"; import { appsManifest } from "../support/apps-release.ts"; import { appLinksFixture, keyProvider, ok, okBody, refused } from "../support/app-links.ts"; import { WorkflowRun } from "../support/workflow-app.ts"; +import { requirementPath } from "../support/app-accounts.ts"; import { scenarios } from "../test-plan.ts"; /** @@ -54,6 +55,19 @@ export default defineApp({ app: { accounts: { team } } }, async () => ({ tools: router({ tick }), schedules: { tick: userInterval({ minutes: 1 }, tick, {}) }, }));`; +/** + * `tick` declared in one scope over the same requirements: an app account linked for everyone and + * a user account each member links for themselves. + */ +const scopeSource = ( + scope: "app" | "user", +) => `import { defineApp, defineProvider, secrets, mutation, ${scope}Interval, object, string, router } from "apps"; +const team = ${keyProvider("App schedule fixture")}; +const tick = mutation({ input: object({}) }, async () => "tick"); +export default defineApp({ app: { accounts: { team } }, user: { accounts: { personal: team } } }, async () => ({ + tools: router({ tick }), + schedules: { tick: ${scope}Interval({ minutes: 1 }, tick, {}) }, +}));`; const migration = { path: "migrations/0001_ticks.sql", content: @@ -193,6 +207,97 @@ layer(HostedLive, { excludeTestServices: true })("App schedules", (it) => { }), ), ); + it.effect(scenarios.hostedAppScheduleScope.title, (context) => + withHostedCase( + context, + Effect.gen(function* () { + // `tick` starts as a user declaration that runs with the member's own key. + const fixture = yield* appLinksFixture([ + { path: "index.ts", content: scopeSource("user") }, + ]); + const { api, actors, prefix, app, path, connect } = fixture; + const configure = (actor: Session, settings: object) => + api.request(actor, "PATCH", `${path}/schedules/tick`, settings); + const runNow = (actor: Session, scope?: "app" | "user") => + api.request( + actor, + "POST", + `${path}/schedules/tick/run${scope === undefined ? "" : `?scope=${scope}`}`, + ); + const succeeded = (count: number) => + api.request(actors.owner, "GET", `${prefix}/scheduled-runs?app=${app.id}`).pipe( + Effect.flatMap((response) => body(Runs, response)), + Effect.flatMap((rows) => + rows.filter((row) => row.status === "succeeded").length >= count + ? Effect.void + : Effect.fail(new Error(`Fewer than ${count} succeeded: ${JSON.stringify(rows)}`)), + ), + Effect.retry({ schedule: Schedule.spaced("200 millis"), times: 100 }), + ); + yield* connect(actors.owner, "app", "team", "team-key"); + const personal = yield* connect(actors.member, "user", "personal", "personal-key"); + + // A user declaration keeps the user scope without one: the member's own copy. + const copy = yield* okBody(Settings, yield* configure(actors.member, { enabled: true })); + expect(copy).toMatchObject({ actor: fixture.ids.member, enabled: true }); + expect((yield* okBody(Settings, yield* runNow(actors.member))).id).toBe(copy.id); + yield* succeeded(1); + // Without their key the member's copy cannot be checked, so a redeploy keeps it. + yield* ok( + yield* api.request( + actors.member, + "DELETE", + `${requirementPath(path, "user", "personal")}/${encodeURIComponent(personal)}`, + ), + ); + + // `tick` becomes an app declaration. With nothing saved for the admin, configuring it + // without a scope follows the declaration to the app schedule. + const redeployed = yield* api.request(actors.owner, "POST", `${path}/deploy`, { + files: [{ path: "index.ts", content: scopeSource("app") }, appsManifest], + }); + expect(redeployed.status, JSON.stringify(redeployed.body)).toBe(200); + const appSchedule = yield* okBody( + Settings, + yield* configure(actors.admin, { enabled: true }), + ); + expect(appSchedule).toMatchObject({ name: "tick", actor: null, enabled: true }); + + // Run now finds the app schedule by name, without and with a scope. + expect((yield* okBody(Settings, yield* runNow(actors.owner))).id).toBe(appSchedule.id); + yield* succeeded(2); + expect((yield* okBody(Settings, yield* runNow(actors.admin, "app"))).id).toBe( + appSchedule.id, + ); + yield* succeeded(3); + // The admin has no copy of their own. + yield* refused(yield* runNow(actors.admin, "user"), 404, "ScheduleNotFound"); + + // Only managers run or configure the app schedule, however it is named. + expect((yield* runNow(actors.member, "app")).status).toBe(403); + expect((yield* configure(actors.member, { enabled: false, scope: "app" })).status).toBe( + 403, + ); + + // The member has both the app schedule and their kept copy under the name: without a + // scope both routes refuse to guess, and with one each acts on the schedule it names. + yield* refused(yield* runNow(actors.member), 409, "ScheduleScopeRequired"); + yield* refused( + yield* configure(actors.member, { enabled: false }), + 409, + "ScheduleScopeRequired", + ); + const paused = yield* okBody( + Settings, + yield* configure(actors.member, { enabled: false, scope: "user" }), + ); + expect(paused).toMatchObject({ id: copy.id, actor: fixture.ids.member, enabled: false }); + expect( + yield* okBody(Settings, yield* configure(actors.owner, { enabled: false })), + ).toMatchObject({ id: appSchedule.id, actor: null, enabled: false }); + }), + ), + ); it.effect(scenarios.hostedAppScopeWorkflows.title, (context) => withHostedCase( context, diff --git a/e2e/tests/local-app-account-app-links.spec.ts b/e2e/tests/local-app-account-app-links.spec.ts index e36d35c5ef..e601e5285e 100644 --- a/e2e/tests/local-app-account-app-links.spec.ts +++ b/e2e/tests/local-app-account-app-links.spec.ts @@ -505,6 +505,30 @@ export default defineApp({ app: { accounts: { x: service } }, user: { accounts: [second, false], ]); expect((yield* runs).map((row) => row.status)).toEqual(["succeeded", "succeeded"]); + + // By name, without a scope, run now and configure find the app schedule; a user scope + // names a local copy, which there is none of. + const byName = (scope?: "app" | "user") => + api.request( + agent, + "POST", + `${path}/tick/run${scope === undefined ? "" : `?scope=${scope}`}`, + ); + const unscoped = yield* byName(); + expect(unscoped.status, JSON.stringify(unscoped.body)).toBe(200); + expect((yield* body(Settings, unscoped)).id).toBe(schedule.id); + yield* succeeded(3); + const scoped = yield* byName("app"); + expect(scoped.status, JSON.stringify(scoped.body)).toBe(200); + yield* succeeded(4); + expect((yield* byName("user")).status).toBe(404); + const paused = yield* api.request(agent, "PATCH", `${path}/tick`, { enabled: false }); + expect(paused.status, JSON.stringify(paused.body)).toBe(200); + expect(yield* body(Settings, paused)).toMatchObject({ + id: schedule.id, + actor: null, + enabled: false, + }); }), ), ); diff --git a/packages/app-templates/executor/skills/app-authoring/workflows.md b/packages/app-templates/executor/skills/app-authoring/workflows.md index 4e2a6b0f77..9bc9d46516 100644 --- a/packages/app-templates/executor/skills/app-authoring/workflows.md +++ b/packages/app-templates/executor/skills/app-authoring/workflows.md @@ -105,7 +105,13 @@ needed. A workflow such a mutation starts declares `WorkflowContext> = { "app-authoring/upgrades/0.0.1-beta.38.md": "0e0e38e0334fbece5bdb8264a32be4f36cef9c51705e8f6b749dc0d3b86dcdb5", "app-authoring/upgrades/0.0.1-beta.90.md": "38c727888b2773efa1d83795e8704f7c38ad9ec27c62fcdd89b5177ec5e338c3", "app-authoring/webhooks.md": "e4ca224cd413b591c3692b389bd88d644b337b4697a067d83551e6bcab657cf3", - "app-authoring/workflows.md": "d738a636715e271690e589112936b03a5da3e2b23a928eb6a50e89a8b9b7dda8", + "app-authoring/workflows.md": "db0dee9a36a2271c4e8f1715605fba8620e11be3668495cdfc6c40cfbb5aaf62", "code-mode/SKILL.md": "40e2efdb28d0973c226126779aa313208db760b079e3ddf6c8cf3713e5d489dc", "executor/SKILL.md": "f58448f79ea529ebadbba8f0e001f2c9fe46f73475b9f6e99423f6d81ff97709", "executor/feedback.md": "11397bd260917e5a21e92897a19368d0426bf5944a7c081adc2c061d1ea797cd" diff --git a/packages/sdk/src/contracts/schedules.ts b/packages/sdk/src/contracts/schedules.ts index ea6bf79eb6..7c5694ed43 100644 --- a/packages/sdk/src/contracts/schedules.ts +++ b/packages/sdk/src/contracts/schedules.ts @@ -12,6 +12,7 @@ import { ToolName, } from "./shared.ts"; import { + AccountScope, AppAccounts, AppAccountsQuery, AppNotDeployed, @@ -148,6 +149,17 @@ export const ScheduleInvalid = ApiError.define({ message: "The schedule's timing does not produce a valid future occurrence.", }); export type ScheduleInvalid = typeof ScheduleInvalid.Type; +/** + * A schedule addressed by name without a scope matched both the app schedule and the caller's own + * copy of a user schedule. The caller names `scope` rather than the server guessing. + */ +export const ScheduleScopeRequired = ApiError.define({ + tag: "ScheduleScopeRequired", + status: 409, + message: + 'Both the app schedule and your own copy of a schedule have this name. Retry with scope "app" for the app schedule or "user" for your copy.', +}); +export type ScheduleScopeRequired = typeof ScheduleScopeRequired.Type; const app = { app: AppId, @@ -182,6 +194,13 @@ export const ScheduleInputs = { }), /** The actor's copy; `ScheduleNotFound` when they have none. */ copy: Schema.Struct(own), + /** + * The scope a by-name request from the actor acts on when it names none. A saved schedule + * decides: the app schedule, or the actor's copy; both saved fails with `ScheduleScopeRequired`. + * With neither, `app` when the app, evaluated as its app schedule runs, declares the name as an + * app schedule, and otherwise `user`. + */ + scope: Schema.Struct({ ...app, name: Schema.NonEmptyString, actor: Schema.NonEmptyString }), /** Pause or resume one copy, or change its approvals. Its actor never changes. */ update: Schema.Struct({ ...copy, @@ -209,6 +228,7 @@ export const ScheduleErrors = [ ScheduleNotFound, ScheduleConflict, ScheduleInvalid, + ScheduleScopeRequired, AppNotFound, AppNotDeployed, AccountRequired, @@ -268,6 +288,17 @@ export const SchedulesGroup = HttpApiGroup.make("schedules") error: ScheduleErrors, }), ) + .add( + HttpApiEndpoint.get("scope", "/v1/apps/:app/schedules/:name/scope", { + params: { app: AppId, name: Schema.NonEmptyString }, + query: { + owner: Schema.optional(OwnerId), + actor: Schema.NonEmptyString, + }, + success: AccountScope, + error: ScheduleErrors, + }), + ) .add( HttpApiEndpoint.patch("update", "/v1/apps/:app/schedules/:name/copies/:copy", { params: { app: AppId, name: Schema.NonEmptyString, copy: ScheduleId }, diff --git a/packages/sdk/src/implementation/handlers.ts b/packages/sdk/src/implementation/handlers.ts index b3bd20643f..51d91a5bff 100644 --- a/packages/sdk/src/implementation/handlers.ts +++ b/packages/sdk/src/implementation/handlers.ts @@ -23,6 +23,7 @@ export const executorHandlers = (executor: Executor) => executor.schedules.configure({ ...params, ...payload }), ) .handle("copy", ({ params, query }) => executor.schedules.copy({ ...params, ...query })) + .handle("scope", ({ params, query }) => executor.schedules.scope({ ...params, ...query })) .handle("update", ({ params, payload }) => executor.schedules.update({ ...params, ...payload }), ) diff --git a/packages/sdk/src/implementation/promise.ts b/packages/sdk/src/implementation/promise.ts index 0df1eb7f72..cc14949162 100644 --- a/packages/sdk/src/implementation/promise.ts +++ b/packages/sdk/src/implementation/promise.ts @@ -83,6 +83,7 @@ export const promiseExecutor = (executor: Executor): PromiseExecutor => { list: (input) => run(ScheduleInputs.list, input, executor.schedules.list), configure: (input) => run(ScheduleInputs.configure, input, executor.schedules.configure), copy: (input) => run(ScheduleInputs.copy, input, executor.schedules.copy), + scope: (input) => run(ScheduleInputs.scope, input, executor.schedules.scope), update: (input) => run(ScheduleInputs.update, input, executor.schedules.update), runNow: (input) => run(ScheduleInputs.runNow, input, executor.schedules.runNow), remove: (input) => run(ScheduleInputs.remove, input, executor.schedules.remove), diff --git a/packages/sdk/src/implementation/schedules.ts b/packages/sdk/src/implementation/schedules.ts index 227caa532e..56dc763683 100644 --- a/packages/sdk/src/implementation/schedules.ts +++ b/packages/sdk/src/implementation/schedules.ts @@ -8,7 +8,7 @@ import { type Executor, type ResourceLifecycle, } from "../contracts/executor.ts"; -import { AccountRequired } from "../contracts/apps.ts"; +import { AccountRequired, type AccountScope } from "../contracts/apps.ts"; import { StorageError, RequestInvalid, @@ -28,6 +28,7 @@ import { ScheduleNotFound, ScheduleConflict, ScheduleInvalid, + ScheduleScopeRequired, } from "../contracts/schedules.ts"; import { InvocationRun } from "../contracts/runtime.ts"; import { ScheduleObservation } from "../contracts/scheduler.ts"; @@ -545,6 +546,27 @@ export const makeSchedules = ( if (found === null) return yield* new ScheduleNotFound(); return found; }), + scope: (input: typeof ScheduleInputs.scope.Type) => + Effect.gen(function* () { + const app = yield* apps.get(input); + const named = { app: app.id, name: input.name }; + const shared = yield* findOwn({ ...named, actor: null }); + const own = yield* findOwn({ ...named, actor: input.actor }); + if (shared !== null && own !== null) return yield* new ScheduleScopeRequired(); + if (shared !== null) return "app" as const; + if (own !== null) return "user" as const; + // Nothing saved: the declaration decides, evaluated with the accounts an app schedule + // runs with, so the caller's own links are not needed. Any failure but storage keeps the + // user scope, whose request then reports its own failure. + return yield* definition({ ...named, actor: null }).pipe( + Effect.as("app"), + Effect.catch((error) => + Schema.is(StorageError)(error) + ? Effect.fail(error) + : Effect.succeed("user"), + ), + ); + }), update: (input: typeof ScheduleInputs.update.Type) => Effect.gen(function* () { const parsed = yield* Schema.decodeUnknownEffect(ScheduleInputs.update)(input).pipe(