Skip to content

Email for professionals and teams

improve auto-update workflow

Hieu Nguyen (Jack)15697a796bfb
diff --git a/.github/workflows/deploy-update.yml b/.github/workflows/deploy-update.yml
index 31f6592..9f46f3e 100644
--- a/.github/workflows/deploy-update.yml
+++ b/.github/workflows/deploy-update.yml
@@ -4,7 +4,7 @@ on:
workflow_dispatch:
permissions:
- contents: write
+ contents: read
jobs:
update:
@@ -13,12 +13,22 @@ jobs:
UPDATE_SOURCE_REPOSITORY: ${{ vars.UPDATE_SOURCE_REPOSITORY || 'hieunc229/mailflare' }}
steps:
+ - name: Check update token
+ env:
+ UPDATE_TOKEN: ${{ secrets.MAILFLARE_UPDATE_TOKEN }}
+ run: |
+ if [ -z "${UPDATE_TOKEN}" ]; then
+ echo "::error::Add MAILFLARE_UPDATE_TOKEN as a repository Actions secret."
+ exit 1
+ fi
+
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 0
+ token: ${{ secrets.MAILFLARE_UPDATE_TOKEN }}
- - name: Merge upstream changes
+ - name: Replace repository with upstream source
run: |
set -euo pipefail
git config user.name "mailflare-update"
@@ -37,15 +47,17 @@ jobs:
echo "::error::Could not resolve the default branch of ${UPDATE_SOURCE_REPOSITORY}."
exit 1
fi
- echo "Merging upstream/${upstream_branch} into ${GITHUB_REF_NAME}."
+ upstream_ref="upstream/${upstream_branch}"
+ echo "Replacing ${GITHUB_REF_NAME} with ${upstream_ref}."
- # A merge keeps local modifications instead of overwriting them, and
- # stops on conflict rather than silently discarding local work.
- if ! git merge --no-edit "upstream/${upstream_branch}"; then
- git merge --abort || true
- echo "::error::Merge conflict with upstream/${upstream_branch}. Resolve it locally and push."
- exit 1
+ # Keep the installation repository's commit history while replacing
+ # its complete tracked tree with the current upstream tree.
+ git read-tree --reset -u "${upstream_ref}"
+ if git diff --cached --quiet; then
+ echo "Repository is already up to date."
+ exit 0
fi
+ git commit -m "Update Mailflare from ${UPDATE_SOURCE_REPOSITORY}@${upstream_branch}"
- name: Push update
run: |
diff --git a/docs/deployment.md b/docs/deployment.md
index cae8d9d..859b396 100644
--- a/docs/deployment.md
+++ b/docs/deployment.md
@@ -81,27 +81,41 @@ After upgrading an existing installation and confirming the cron trigger is acti
## Updating Mailflare
-The **Update Mailflare** button in the admin dashboard dispatches `.github/workflows/deploy-update.yml` in the installation repository. The workflow merges the latest upstream source and pushes the updated source. A connected Cloudflare Git integration then builds and deploys the change.
+The **Update Mailflare** button in the admin dashboard dispatches `.github/workflows/deploy-update.yml` in the installation repository. The workflow replaces the installation branch's complete tracked tree with the latest upstream source, commits that replacement, and pushes it. This avoids merge conflicts between independently created installation and upstream histories. Target-only committed files and code changes are intentionally removed; repository variables, secrets, and other GitHub or Cloudflare configuration remain unchanged. A connected Cloudflare Git integration then builds and deploys the change.
-Deployment and database migration are separate. After Cloudflare deploys a repository push or an admin-triggered update, open or refresh **Admin settings**. The application update card shows any pending database migrations. Select **Update database** to apply them through the Worker's D1 binding. The same runner initializes a new database during setup.
+### Auto update
-If the Cloudflare dashboard has a custom deploy command containing `wrangler d1 migrations apply DB --remote`, remove that part and use `npm run deploy`.
+Create a fine-grained personal access token for the installation repository with these repository permissions:
-Each migration and its `d1_migrations` history entry run in one D1 batch. If a migration fails, its changes are rolled back, the failed filename is shown, and it can be retried after the problem is corrected. Wrangler remains available as a manual recovery tool.
+| Permission | Access | Used for |
+| --- | --- | --- |
+| Actions | Read and write | Dispatching `deploy-update.yml` from the Mailflare admin dashboard |
+| Contents | Read and write | Committing and pushing the upstream source into the installation repository |
+| Workflows | Read and write | Replacing files inside `.github/workflows` during an update |
-New application releases must remain compatible with the previous schema until an administrator applies their migrations. Prefer additive changes, keep old columns during the transition, and avoid making authentication or the admin settings page depend immediately on a newly added column. Plan a maintenance window for an incompatible schema change.
+Configure the token and repository details in both Cloudflare and GitHub:
+
+| Location | Name | Type | Value |
+| --- | --- | --- | --- |
+| Cloudflare Worker | `GITHUB_UPDATE_TOKEN` | Secret | The fine-grained personal access token |
+| Cloudflare Worker | `GITHUB_UPDATE_REPO` | Variable | The installation repository in `owner/repository` format |
+| Cloudflare Worker | `GITHUB_UPDATE_REF` | Optional variable | The installation branch to update; omit it to use the repository's default branch |
+| GitHub repository → Actions | `MAILFLARE_UPDATE_TOKEN` | Repository secret | The same fine-grained personal access token |
+| GitHub repository → Actions | `UPDATE_SOURCE_REPOSITORY` | Optional repository variable | The upstream repository; defaults to `hieunc229/mailflare` |
-Configure these Worker values:
+The same token can be used for `GITHUB_UPDATE_TOKEN` and `MAILFLARE_UPDATE_TOKEN` when it has all three permissions above. Keep both values secret and limit the token's repository access to the installation repository.
-- `GITHUB_UPDATE_TOKEN` — a fine-grained GitHub token for the installation repository with Actions write permission.
-- `GITHUB_UPDATE_REPO` — the installation repository in `owner/repository` format.
-- `GITHUB_UPDATE_REF` — an optional update branch. The repository's default branch is used when omitted.
+Make sure `.github/workflows/deploy-update.yml` exists on the installation branch. If it is missing, create the file and copy its contents from the [canonical Mailflare update workflow](https://github.com/hieunc229/mailflare/blob/main/.github/workflows/deploy-update.yml). If an older installation has a different updater, replace it with the latest canonical workflow once. A running workflow cannot create or replace itself until the current workflow has been installed manually.
-Optional repository variables:
+After the GitHub Action completes successfully, wait for the connected Cloudflare deployment to finish before refreshing Mailflare or applying pending database migrations. The workflow updates the repository first; the new application version is not live until Cloudflare completes its deployment.
-- `UPDATE_SOURCE_REPOSITORY` — the upstream repository. Defaults to `hieunc229/mailflare`.
+Deployment and database migration are separate. After Cloudflare deploys a repository push or an admin-triggered update, open or refresh **Admin settings**. The application update card shows any pending database migrations. Select **Update database** to apply them through the Worker's D1 binding. The same runner initializes a new database during setup.
-If an older installation still runs migrations in its updater, copy the latest `.github/workflows/deploy-update.yml` into that installation once. A workflow already running cannot update itself before executing its old migration step.
+If the Cloudflare dashboard has a custom deploy command containing `wrangler d1 migrations apply DB --remote`, remove that part and use `npm run deploy`.
+
+Each migration and its `d1_migrations` history entry run in one D1 batch. If a migration fails, its changes are rolled back, the failed filename is shown, and it can be retried after the problem is corrected. Wrangler remains available as a manual recovery tool.
+
+New application releases must remain compatible with the previous schema until an administrator applies their migrations. Prefer additive changes, keep old columns during the transition, and avoid making authentication or the admin settings page depend immediately on a newly added column. Plan a maintenance window for an incompatible schema change.
When adding a schema change, create a new uniquely named SQL file in `drizzle/migrations` and do not edit an applied migration. Build and development commands generate the Worker migration bundle from those files. `npm run db:bundle` can generate it explicitly.
diff --git a/package.json b/package.json
index 7d13670..32b5a0b 100644
--- a/package.json
+++ b/package.json
@@ -39,7 +39,7 @@
"description": "Worker name used when creating Cloudflare Email Routing rules. Set this to the deployed Worker name; if you rename the Worker, update this value too."
},
"GITHUB_UPDATE_TOKEN": {
- "description": "Fine-grained GitHub token for the installation repository with Actions: write permission, Contents: write read permission. Used only by the admin update endpoint to dispatch deploy-update.yml."
+ "description": "Fine-grained GitHub token for the installation repository with Actions: write permission. Used by the admin update endpoint to dispatch deploy-update.yml."
},
"GITHUB_UPDATE_REF": {
"description": "Optional branch used to dispatch updates. Leave blank to use the repository default branch."
diff --git a/src/app/api/admin/update/types.d.ts b/src/app/api/admin/update/types.d.ts
index e983917..73f8fa3 100644
--- a/src/app/api/admin/update/types.d.ts
+++ b/src/app/api/admin/update/types.d.ts
@@ -19,6 +19,11 @@ export interface PackageMetadata {
version?: string;
}
+export interface UpdateConfigurationItem {
+ configured: boolean;
+ name: "GITHUB_UPDATE_REPO" | "GITHUB_UPDATE_TOKEN";
+}
+
export interface UpdateDispatchConfig {
repository: string;
ref?: string;
@@ -26,8 +31,10 @@ export interface UpdateDispatchConfig {
}
export interface UpdateStatus {
- available: boolean;
+ available?: boolean;
+ configuration: UpdateConfigurationItem[];
+ configured: boolean;
currentVersion: string;
- repository: string;
- targetVersion: string;
+ repository?: string;
+ targetVersion?: string;
}
diff --git a/src/app/api/admin/update/utils.ts b/src/app/api/admin/update/utils.ts
index e0a9136..fb4139f 100644
--- a/src/app/api/admin/update/utils.ts
+++ b/src/app/api/admin/update/utils.ts
@@ -7,6 +7,7 @@ import type {
GitHubRepositoryResponse,
GitHubWorkflowDispatchResponse,
PackageMetadata,
+ UpdateConfigurationItem,
UpdateDispatchConfig,
UpdateStatus,
} from "./types";
@@ -58,6 +59,19 @@ function getDispatchConfig(env: CloudflareEnv): UpdateDispatchConfig {
return { token, repository, ref: ref || undefined };
}
+function getUpdateConfiguration(env: CloudflareEnv): UpdateConfigurationItem[] {
+ return [
+ {
+ name: "GITHUB_UPDATE_TOKEN",
+ configured: !!env.GITHUB_UPDATE_TOKEN?.trim(),
+ },
+ {
+ name: "GITHUB_UPDATE_REPO",
+ configured: !!env.GITHUB_UPDATE_REPO?.trim(),
+ },
+ ];
+}
+
async function githubRequest<T>(
path: string,
init?: RequestInit,
@@ -167,12 +181,25 @@ async function getTargetVersion(): Promise<string> {
export async function getUpdateStatus(
env: CloudflareEnv,
): Promise<UpdateStatus> {
- const config = getDispatchConfig(env);
const currentVersion = packageMetadata.version;
+ const configuration = getUpdateConfiguration(env);
+ const configured = configuration.every((item) => item.configured);
+
+ if (!configured) {
+ return {
+ configuration,
+ configured,
+ currentVersion,
+ };
+ }
+
+ getDispatchConfig(env);
const targetVersion = await getTargetVersion();
return {
available: isNewerVersion(targetVersion, currentVersion),
+ configuration,
+ configured,
currentVersion,
repository: UPDATE_SOURCE_REPOSITORY,
targetVersion,
diff --git a/src/components/admin-update-card-types.d.ts b/src/components/admin-update-card-types.d.ts
index 64a2720..3f3f9e9 100644
--- a/src/components/admin-update-card-types.d.ts
+++ b/src/components/admin-update-card-types.d.ts
@@ -1,5 +1,12 @@
+export interface UpdateConfigurationItem {
+ configured: boolean;
+ name: "GITHUB_UPDATE_REPO" | "GITHUB_UPDATE_TOKEN";
+}
+
export interface UpdateStatusResponse {
available?: boolean;
+ configuration?: UpdateConfigurationItem[];
+ configured?: boolean;
currentVersion?: string;
error?: string;
repository?: string;
diff --git a/src/components/admin-update-card.tsx b/src/components/admin-update-card.tsx
index 3081a10..8866e9c 100644
--- a/src/components/admin-update-card.tsx
+++ b/src/components/admin-update-card.tsx
@@ -1,8 +1,7 @@
"use client";
import { useEffect, useState } from "react";
-import { RefreshCw } from "lucide-react";
-import { Button } from "@/components/ui/button";
+import { CheckCircle2, CircleX, Database, RefreshCw } from "lucide-react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Skeleton } from "@/components/ui/skeleton";
import {
@@ -100,54 +99,99 @@ export function AdminUpdateCard() {
</div>
</CardHeader>
<CardContent className="space-y-5 pt-5">
- <div className="flex items-center gap-4">
- <Button type="button" onClick={handleUpdate} disabled={isChecking || isPending || !status?.available}>
- <RefreshCw className={isPending ? "h-4 w-4 animate-spin" : "h-4 w-4"} />
- {isPending ? "Starting update..." : "Update Mailflare"}
- </Button>
- {isChecking && <Skeleton className="h-4 w-44" />}
- {!isChecking && status?.available && (
- <p className="text-sm text-amber-700">
- Update available: v{status.currentVersion} → v{status.targetVersion}
- </p>
- )}
- {!isChecking && status && !status.available && (
- <p className="text-sm text-green-700">Mailflare v{status.currentVersion} is up to date.</p>
- )}
- {result?.ok && (
- <p className="text-sm text-green-700">
- Update started for {result.repository}@{result.ref}. Refresh this page after Cloudflare deploys it. {" "}
- {result.runUrl && (
- <a className="font-medium underline" href={result.runUrl} target="_blank" rel="noreferrer">
- View workflow
- </a>
+ {isChecking && <Skeleton className="h-20 w-full rounded-2xl" />}
+
+ {!isChecking && status?.configured === false && (
+ <div className="space-y-3">
+ <p className="text-sm text-neutral-600">Complete the required Cloudflare Worker configuration:</p>
+ <ul className="divide-y divide-neutral-100 overflow-hidden rounded-2xl border border-neutral-100">
+ {status.configuration?.map((item) => (
+ <li key={item.name} className="flex items-center gap-3 px-4 py-3 text-sm">
+ {item.configured ? (
+ <CheckCircle2 className="h-4 w-4 shrink-0 text-green-600" />
+ ) : (
+ <CircleX className="h-4 w-4 shrink-0 text-red-600" />
+ )}
+ <code className="text-xs font-medium text-neutral-800">{item.name}</code>
+ <span className={`ml-auto text-xs font-medium ${item.configured ? "text-green-700" : "text-red-600"}`}>
+ {item.configured ? "Configured" : "Missing"}
+ </span>
+ </li>
+ ))}
+ </ul>
+ </div>
+ )}
+
+ {!isChecking && status?.configured && (
+ <div className="divide-y divide-neutral-100 overflow-hidden rounded-2xl border border-neutral-100">
+ <div className="flex items-center gap-3 px-4 py-4">
+ {status.available ? (
+ <RefreshCw className={`h-4 w-4 shrink-0 text-blue-600 ${isPending ? "animate-spin" : ""}`} />
+ ) : (
+ <CheckCircle2 className="h-4 w-4 shrink-0 text-green-600" />
)}
- </p>
- )}
- {error && <p className="text-sm text-red-600">{error}</p>}
- </div>
- <div className="flex items-center gap-4 border-t border-neutral-100 pt-5">
- <Button
- type="button"
- onClick={handleMigrate}
- disabled={isCheckingMigrations || isMigrating || !migrationStatus?.pending.length || !!migrationStatus.unknown.length}
- >
- <RefreshCw className={isMigrating ? "h-4 w-4 animate-spin" : "h-4 w-4"} />
- {isMigrating ? "Updating database..." : "Update database"}
- </Button>
- {isCheckingMigrations && <Skeleton className="h-4 w-44" />}
- {migrationStatus?.pending.length ? (
- <p className="text-sm text-amber-700">
- {migrationStatus.pending.length} database {migrationStatus.pending.length === 1 ? "migration" : "migrations"} pending.
- </p>
- ) : migrationStatus?.ready ? (
- <p className="text-sm text-green-700">Database schema is up to date.</p>
- ) : null}
- {!!migrationStatus?.unknown.length && (
- <p className="text-sm text-red-600">Deploy the matching Mailflare release before changing this database.</p>
- )}
- {migrationError && <p className="text-sm text-red-600">{migrationError}</p>}
- </div>
+ <p className="min-w-0 text-sm text-neutral-700">
+ {status.available
+ ? `Mailflare v${status.targetVersion} is available. You are using v${status.currentVersion}.`
+ : `Mailflare v${status.currentVersion} is up to date.`}
+ </p>
+ {status.available && (
+ <button
+ type="button"
+ onClick={handleUpdate}
+ disabled={isPending}
+ className="ml-auto shrink-0 text-sm font-medium text-blue-700 hover:underline disabled:pointer-events-none disabled:opacity-50"
+ >
+ {isPending ? "Starting update..." : "Update Mailflare"}
+ </button>
+ )}
+ </div>
+
+ {isCheckingMigrations && (
+ <div className="flex items-center gap-3 px-4 py-4">
+ <Skeleton className="h-4 w-4 rounded-full" />
+ <Skeleton className="h-4 w-44" />
+ </div>
+ )}
+
+ {!isCheckingMigrations && !!migrationStatus?.pending.length && !migrationStatus.unknown.length && (
+ <div className="flex items-center gap-3 px-4 py-4">
+ <Database className={`h-4 w-4 shrink-0 text-amber-600 ${isMigrating ? "animate-pulse" : ""}`} />
+ <p className="text-sm text-neutral-700">
+ {migrationStatus.pending.length} database {migrationStatus.pending.length === 1 ? "migration is" : "migrations are"} pending.
+ </p>
+ <button
+ type="button"
+ onClick={handleMigrate}
+ disabled={isMigrating}
+ className="ml-auto shrink-0 text-sm font-medium text-blue-700 hover:underline disabled:pointer-events-none disabled:opacity-50"
+ >
+ {isMigrating ? "Updating database..." : "Update database"}
+ </button>
+ </div>
+ )}
+
+ {!isCheckingMigrations && !!migrationStatus?.unknown.length && (
+ <div className="flex items-center gap-3 px-4 py-4 text-sm text-red-600">
+ <CircleX className="h-4 w-4 shrink-0" />
+ Deploy the matching Mailflare release before changing this database.
+ </div>
+ )}
+ </div>
+ )}
+
+ {result?.ok && (
+ <p className="text-sm text-green-700">
+ Update started for {result.repository}@{result.ref}. Refresh this page after Cloudflare deploys it. {" "}
+ {result.runUrl && (
+ <a className="font-medium underline" href={result.runUrl} target="_blank" rel="noreferrer">
+ View workflow
+ </a>
+ )}
+ </p>
+ )}
+ {error && <p className="text-sm text-red-600">{error}</p>}
+ {migrationError && <p className="text-sm text-red-600">{migrationError}</p>}
</CardContent>
</Card>
);