1
-import { Cause, Config, Console, Effect, Option, Path, Schema, Stdio, Stream } from 'effect';
1
+import { Config, Effect, Option, Path, Schema, Stdio, Stream } from 'effect';
2
import { Base64 } from 'effect/encoding';
3
import { readReleasePull, verifyReleaseGate } from './approval';
4
import {
11
Sha,
12
TagRef,
13
commentIssue,
14
+ fileAt,
15
fileAtOrNull,
16
paginateArray,
17
request,
27
ensure,
28
fail,
29
readJson,
29
- ReleaseError,
30
runMain,
31
sameJson,
32
type ReleaseServices,
36
ReleaseBatch,
37
ReleasePatch,
38
releaseOutputs,
39
+ releaseTag,
40
validateReleaseDiff,
41
} from './source';
42
+import { ReleaseState } from './state';
43
44
const Commit = Schema.Struct({
45
sha: Sha,
54
Pull
55
).pipe(Stream.filter(isReleasePull), Stream.runHead);
56
55
-const causeMessage = (cause: Cause.Cause<unknown>) => {
56
- const error = Cause.squash(cause);
57
- return error instanceof Error ? error.message : 'Release request failed';
58
-};
57
+/**
58
+ * The id of a release plan committed on `sha` whose tag was never created: its release PR merged
59
+ * but failed the gate, or its tag job has not finished. Only the id is read, so older plan shapes
60
+ * still decode.
61
+ */
62
+const untaggedRelease = (sha: string) =>
63
+ Effect.gen(function* () {
64
+ const committed = yield* fileAt(BATCH_PATH, sha);
65
+ if (Option.isNone(committed)) return Option.none<string>();
66
+ const { id } = yield* Schema.decodeUnknownEffect(
67
+ Schema.fromJsonString(Schema.Struct({ id: RunId }))
68
+ )(committed.value);
69
+ const tag = yield* requestOptional(`${REPOSITORY_PATH}/git/ref/tags/${releaseTag(id)}`, TagRef);
70
+ return Option.isNone(tag) ? Option.some(id) : Option.none<string>();
71
+ });
72
73
// 1. request -----------------------------------------------------------------------------------
74
79
readonly issueNumber?: number;
80
}
81
69
-export interface ReleaseRequestResult {
70
- readonly message: string;
71
- readonly batch?: ReleaseBatch;
72
-}
82
+/** A request either ends the request stage or plans a batch for the release PR jobs. */
83
+export type RequestOutcome =
84
+ { readonly _tag: 'Planned'; readonly batch: ReleaseBatch } | ReleaseState;
85
86
/** Opens the tracking issue for a dispatch-started release; issue-form requests already have one. */
87
const createRequestIssue = (run: string) =>
94
);
95
96
/**
85
- * Checks that the requester is an active ComposioHQ member, plans versions, and replies on the
86
- * request issue. Returns the batch to prepare, or only a message when there is nothing to do.
97
+ * Checks that the requester is an active ComposioHQ member, then decides the request: resume
98
+ * its own open release PR, wait for another one, refuse while an untagged release sits on
99
+ * `next`, or plan versions. The request issue shows the outcome; nothing is posted here.
100
*/
101
export const executeReleaseRequest = <E, R>(
89
- value: ReleaseRequest,
102
+ parse: Effect.Effect<ReleaseRequest, string>,
103
context: ReleaseRequestContext,
104
plan: (request: ReleaseRequest) => Effect.Effect<SdkReleasePlan, E, R>
105
) =>
106
Effect.gen(function* () {
94
- const releaseRequest = yield* Schema.decodeUnknownEffect(ReleaseRequest)(value);
107
yield* requireActiveMember(context.actor);
96
- const reply = (text: string) =>
97
- context.issueNumber === undefined ? Effect.void : commentIssue(context.issueNumber, text);
98
- return yield* Effect.gen(function* () {
99
- const current = yield* activeRelease;
100
- if (Option.isSome(current)) {
101
- const result: ReleaseRequestResult = {
102
- message: `Another SDK release is in progress: ${current.value.html_url}. Request this release again after it finishes.`,
103
- };
104
- yield* reply(result.message);
105
- return result;
106
- }
107
- const selected = yield* plan(releaseRequest);
108
- if (!selected.releases.length) {
109
- const result: ReleaseRequestResult = { message: 'Nothing to release.' };
110
- yield* reply(result.message);
111
- return result;
112
- }
113
- const issue = context.issueNumber ?? (yield* createRequestIssue(context.runId));
114
- const batch = yield* Schema.decodeUnknownEffect(ReleaseBatch)({
115
- id: context.runId,
116
- inputBase: context.sourceSha,
117
- requestedBy: context.actor,
118
- issue,
119
- date: new Date().toISOString().slice(0, 10),
120
- plan: selected,
108
+ return yield* parse.pipe(
109
+ Effect.matchEffect({
110
+ onFailure: reason =>
111
+ Effect.succeed<RequestOutcome>(ReleaseState.make({ _tag: 'NeedsInput', reason })),
112
+ onSuccess: releaseRequest => decideRequest(releaseRequest, context, plan),
113
+ })
114
+ );
115
+ });
116
+
117
+const decideRequest = <E, R>(
118
+ releaseRequest: ReleaseRequest,
119
+ context: ReleaseRequestContext,
120
+ plan: (request: ReleaseRequest) => Effect.Effect<SdkReleasePlan, E, R>
121
+) =>
122
+ Effect.gen(function* () {
123
+ const current = yield* activeRelease;
124
+ if (Option.isSome(current))
125
+ return ReleaseState.make({
126
+ _tag: current.value.head.ref === releaseBranch(context.runId) ? 'InReview' : 'Waiting',
127
+ pull: current.value.html_url,
128
});
122
- // The batch travels as one environment variable, which Linux caps at 128 KiB.
123
- yield* ensure(
124
- new TextEncoder().encode(JSON.stringify(batch)).length < 120_000,
125
- 'Release batch is too large to pass between jobs'
126
- );
127
- const result: ReleaseRequestResult = {
128
- message: `Planned. The release PR opens from ${runUrl(context.runId)}.`,
129
- batch,
130
- };
131
- yield* reply(result.message);
132
- return result;
133
- }).pipe(
134
- Effect.tapCause(cause =>
135
- reply(
136
- `The release request could not complete: ${causeMessage(cause)}\n\nInspect this request run: ${runUrl(context.runId)}`
137
- ).pipe(
138
- Effect.catchCause(reportCause =>
139
- Console.error(
140
- 'Could not report the release request failure:',
141
- causeMessage(reportCause)
142
- )
143
- )
144
- )
145
- )
129
+ const untagged = yield* untaggedRelease(context.sourceSha);
130
+ if (Option.isSome(untagged))
131
+ return ReleaseState.make({ _tag: 'Blocked', release: untagged.value });
132
+ const selected = yield* plan(releaseRequest);
133
+ if (!selected.releases.length) return ReleaseState.make({ _tag: 'Empty' });
134
+ const issue = context.issueNumber ?? (yield* createRequestIssue(context.runId));
135
+ const batch = yield* Schema.decodeUnknownEffect(ReleaseBatch)({
136
+ id: context.runId,
137
+ inputBase: context.sourceSha,
138
+ requestedBy: context.actor,
139
+ issue,
140
+ date: new Date().toISOString().slice(0, 10),
141
+ plan: selected,
142
+ });
143
+ // The batch travels as one environment variable, which Linux caps at 128 KiB.
144
+ yield* ensure(
145
+ new TextEncoder().encode(JSON.stringify(batch)).length < 120_000,
146
+ 'Release batch is too large to pass between jobs'
147
);
148
+ return { _tag: 'Planned', batch } as RequestOutcome;
149
});
150
151
// 2. release PR --------------------------------------------------------------------------------
212
const batch = yield* Schema.decodeUnknownEffect(ReleaseBatch)(planned);
213
const patch = yield* Schema.decodeUnknownEffect(ReleasePatch)(value);
214
const current = yield* activeRelease;
213
- if (Option.isSome(current)) {
214
- // A re-run after the PR opened repeats the issue link in case that comment failed.
215
- if (current.value.head.ref === releaseBranch(batch.id)) {
216
- yield* commentIssue(batch.issue, `Release PR: ${current.value.html_url}`);
217
- return current.value.html_url;
218
- }
219
- // Not a failure of this run: the requester is told what to do, and nothing was created.
220
- yield* commentIssue(
221
- batch.issue,
222
- `Another SDK release is in progress: ${current.value.html_url}. Request this release again after it finishes.`
223
- );
224
- return undefined;
225
- }
215
+ // A re-run after the PR opened finds its own PR; any other open release PR wins.
216
+ if (Option.isSome(current))
217
+ return ReleaseState.make({
218
+ _tag: current.value.head.ref === releaseBranch(batch.id) ? 'InReview' : 'Waiting',
219
+ pull: current.value.html_url,
220
+ });
221
const frozen = yield* Effect.forEach(
222
patch.files,
223
file => fileAtOrNull(file.path, batch.inputBase),
247
base: 'next',
248
body: releasePullBody(batch, branch, outputs),
249
});
255
- yield* commentIssue(batch.issue, `Release PR: ${pull.html_url}`);
256
- return pull.html_url;
250
+ return ReleaseState.make({ _tag: 'InReview', pull: pull.html_url });
251
});
252
253
// 3. tag ---------------------------------------------------------------------------------------
254
255
/**
262
- * Explains a merged release that did not pass its gate on the PR and its request issue. Only a
263
- * gate verdict asks for a revert; a GitHub or transport error asks for a re-run instead.
256
+ * Decides a closed release PR. An unmerged PR is abandoned. A merged one is tagged on its reviewed
257
+ * head only if it passes the release gate; a gate verdict refuses it and says so on the PR, while
258
+ * a GitHub or transport error fails the job so "Re-run failed jobs" retries it. GitHub records the
259
+ * head and the squash commit separately, so a single-parent squash need not list the head.
260
*/
265
-const reportRefusedRelease = (pull: Pull, batch: ReleaseBatch, cause: Cause.Cause<unknown>) => {
266
- const body = (
267
- Cause.squash(cause) instanceof ReleaseError
268
- ? [
269
- `Release PR #${pull.number} merged, but it failed the release gate, so no publication tag was created and nothing was published.`,
270
- `Reason: ${causeMessage(cause)}`,
271
- 'Revert this release PR on next, then request the release again.',
272
- ]
273
- : [
274
- `Release PR #${pull.number} merged, but the release gate could not complete, so no publication tag was created and nothing was published.`,
275
- `Error: ${causeMessage(cause)}`,
276
- 'Use "Re-run failed jobs" on the tag job; creating the tag is safe to repeat.',
277
- ]
278
- ).join('\n\n');
279
- return Effect.gen(function* () {
280
- yield* commentIssue(pull.number, body);
281
- yield* commentIssue(batch.issue, body);
282
- }).pipe(
283
- Effect.catchCause(reportCause =>
284
- Console.error('Could not report the refused release:', causeMessage(reportCause))
285
- )
286
- );
287
-};
288
-
289
-/**
290
- * Creates the immutable publication tag on the reviewed head. GitHub records that head and the
291
- * squash commit separately, so a single-parent squash need not list the head as a parent.
292
- */
293
-export const authorizeSourceTag = (number: number, appSlug: string) =>
261
+export const authorizeSourceTag = (pull: Pull, batch: ReleaseBatch, appSlug: string) =>
262
Effect.gen(function* () {
295
- const { pull, batch } = yield* readReleasePull(number);
296
- if (!pull.merged || !pull.merge_commit_sha) return yield* fail('Release PR has not merged');
297
- yield* verifyReleaseGate(pull, batch, appSlug).pipe(
298
- Effect.tapCause(cause => reportRefusedRelease(pull, batch, cause))
263
+ if (!pull.merged || !pull.merge_commit_sha)
264
+ return ReleaseState.make({ _tag: 'Abandoned', pull: pull.html_url });
265
+ const verdict = yield* verifyReleaseGate(pull, batch, appSlug).pipe(
266
+ Effect.as(Option.none<string>()),
267
+ Effect.catchTag('ReleaseError', error => Effect.succeedSome(error.message))
268
);
269
+ if (Option.isSome(verdict)) {
270
+ yield* commentIssue(
271
+ pull.number,
272
+ `This release PR merged, but it failed the release gate, so nothing was tagged or published.\n\nReason: ${verdict.value}\n\nRevert it on \`next\`, then request the release again.`
273
+ );
274
+ return ReleaseState.make({ _tag: 'Refused', pull: pull.html_url, reason: verdict.value });
275
+ }
276
const merged = yield* request(
277
'GET',
278
`${REPOSITORY_PATH}/git/commits/${pull.merge_commit_sha}`,
282
merged.parents.some(parent => parent.sha === pull.head.sha) || merged.parents.length === 1,
283
'Unrecognized release merge topology'
284
);
309
- const tag = `sdk-release/${batch.id}`;
285
+ const tag = releaseTag(batch.id);
286
const existing = yield* requestOptional(`${REPOSITORY_PATH}/git/ref/tags/${tag}`, TagRef);
287
yield* Option.match(existing, {
288
onSome: ref =>
296
sha: pull.head.sha,
297
}),
298
});
323
- return tag;
299
+ return ReleaseState.make({ _tag: 'Tagged', tag });
300
});
301
302
// entry point ----------------------------------------------------------------------------------
308
eventPath: Config.String('GITHUB_EVENT_PATH'),
309
eventName: Config.String('GITHUB_EVENT_NAME'),
310
outputPath: Config.String('GITHUB_OUTPUT'),
335
- summaryPath: Config.String('GITHUB_STEP_SUMMARY'),
311
});
312
type Environment = Config.Success<typeof Environment>;
313
325
envelope: typeof EventEnvelope.Type
326
) => Effect.Effect<void, unknown, GitHub | ReleaseServices>;
327
328
+/** Writes a stage outcome as a job output for the stage's status job. */
329
+const outputState = (env: Environment, state: ReleaseState) =>
330
+ appendFile(env.outputPath, `state=${JSON.stringify(state)}\n`);
331
+
332
const MODES: Record<'plan' | 'release-pr' | 'tag', Mode> = {
333
plan: (env: Environment, event: unknown, envelope: typeof EventEnvelope.Type) =>
334
Effect.gen(function* () {
335
const cwd = (yield* Path.Path).resolve('.');
357
- const releaseRequest = yield* Effect.try(() => parseReleaseRequest(env.eventName, event));
358
- const result = yield* executeReleaseRequest(
359
- releaseRequest,
336
+ // Known before planning, so a failure is still reported on the request issue.
337
+ if (envelope.issue) yield* appendFile(env.outputPath, `issue=${envelope.issue.number}\n`);
338
+ const outcome = yield* executeReleaseRequest(
339
+ Effect.try({
340
+ try: () => parseReleaseRequest(env.eventName, event),
341
+ catch: error => (error instanceof Error ? error.message : 'Unreadable request'),
342
+ }),
343
{
344
actor: envelope.sender.login,
345
runId: env.runId,
348
},
349
choices => createSdkReleasePlan(cwd, choices)
350
);
368
- if (result.batch) {
369
- yield* appendFile(env.outputPath, `batch=${JSON.stringify(result.batch)}\n`);
370
- }
371
- yield* appendFile(env.summaryPath, `${result.message}\n`);
351
+ yield* outcome._tag === 'Planned'
352
+ ? appendFile(
353
+ env.outputPath,
354
+ `batch=${JSON.stringify(outcome.batch)}\nissue=${outcome.batch.issue}\n`
355
+ )
356
+ : outputState(env, outcome);
357
}),
358
'release-pr': (env: Environment) =>
359
Effect.gen(function* () {
360
const [, patchPath] = yield* (yield* Stdio.Stdio).args;
361
if (!patchPath) return yield* fail('Expected the prepared patch path');
377
- const url = yield* openReleasePull(
362
+ const state = yield* openReleasePull(
363
(yield* Path.Path).resolve('.'),
364
yield* plannedBatch,
365
yield* readJson(Schema.Unknown, patchPath)
366
);
382
- yield* appendFile(
383
- env.summaryPath,
384
- url ? `Release PR: ${url}\n` : 'Another SDK release is in progress.\n'
385
- );
367
+ yield* outputState(env, state);
368
}),
369
tag: (env: Environment, _event: unknown, envelope: typeof EventEnvelope.Type) =>
370
Effect.gen(function* () {
389
- if (!envelope.pull_request) return yield* fail('Expected merged release PR event');
371
+ if (!envelope.pull_request) return yield* fail('Expected a closed release PR event');
372
const appSlug = yield* Config.String('SDK_RELEASE_APP_SLUG');
391
- const tag = yield* authorizeSourceTag(envelope.pull_request.number, appSlug);
392
- yield* appendFile(env.summaryPath, `Approved publication source: ${tag}\n`);
373
+ const { pull, batch } = yield* readReleasePull(envelope.pull_request.number);
374
+ yield* appendFile(env.outputPath, `issue=${batch.issue}\n`);
375
+ yield* outputState(env, yield* authorizeSourceTag(pull, batch, appSlug));
376
}),
377
};
378