mirror of
https://github.com/tiennm99/claude-code-routine-trigger.git
synced 2026-10-17 08:14:20 +00:00
Compare commits
2
Commits
v0.1.0
..
9d0fcc3708
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9d0fcc3708 | ||
|
|
3119e186ed |
No files matched your search
@@ -4,6 +4,20 @@
|
|||||||
> **No longer used by the author.** Claude Code routines now ship with a **built-in cron trigger** in the routine editor — that's what I use now. Prefer the native scheduler; it runs on Anthropic's infra (no GitHub Actions delay/drop issues), needs no repo, no secrets, no workflow file.
|
> **No longer used by the author.** Claude Code routines now ship with a **built-in cron trigger** in the routine editor — that's what I use now. Prefer the native scheduler; it runs on Anthropic's infra (no GitHub Actions delay/drop issues), needs no repo, no secrets, no workflow file.
|
||||||
>
|
>
|
||||||
> This repo is kept as a reference for anyone who still wants to fire routines from an external scheduler (GitHub Actions, own cron, Cloud Scheduler, etc.).
|
> This repo is kept as a reference for anyone who still wants to fire routines from an external scheduler (GitHub Actions, own cron, Cloud Scheduler, etc.).
|
||||||
|
>
|
||||||
|
> If you want **self-hosted scheduling with sub-second precision** (no GitHub cron delays/drops), see the sibling repo: [tiennm99/claude-code-routine-cron](https://github.com/tiennm99/claude-code-routine-cron) — Go daemon shipped as a multi-arch Docker image on GHCR.
|
||||||
|
|
||||||
|
## Choose your deployment
|
||||||
|
|
||||||
|
| | **claude-code-routine-trigger** (this) | [claude-code-routine-cron](https://github.com/tiennm99/claude-code-routine-cron) | [claude-code-routine-trigger-worker](https://github.com/tiennm99/claude-code-routine-trigger-worker) |
|
||||||
|
| ---------------- | -------------------------------------- | -------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- |
|
||||||
|
| Runs on | GitHub Actions runners | your infra (Docker, k8s, NAS, RPi) | Cloudflare edge |
|
||||||
|
| Cost | free (within GitHub minutes) | minimal (your infra) | free (CF free tier) |
|
||||||
|
| Cron precision | ±30 min – 2 h, can drop runs | sub-second | within ~15 sec |
|
||||||
|
| Setup | fork + 2 repo secrets | env vars + Docker | `wrangler deploy` + 2 secrets |
|
||||||
|
| Audit trail | GitHub Actions runs page | container stdout | CF dashboard / `wrangler tail` |
|
||||||
|
|
||||||
|
Pick **this repo** if you want zero-infra and don't care about precise firing time. Pick **-cron** for behind-firewall / on-prem / precise timing. Pick **-worker** for edge-native deploys with CF dashboard observability.
|
||||||
|
|
||||||
Scheduled GitHub Actions workflow that fires a [Claude Code routine](https://code.claude.com/docs/en/routines) via the [`/fire` API](https://platform.claude.com/docs/en/api/claude-code/routines-fire). Ships with a 5×-daily default cron and exposes a `workflow_dispatch` button for on-demand runs. Fire URL and per-routine token live in repo secrets.
|
Scheduled GitHub Actions workflow that fires a [Claude Code routine](https://code.claude.com/docs/en/routines) via the [`/fire` API](https://platform.claude.com/docs/en/api/claude-code/routines-fire). Ships with a 5×-daily default cron and exposes a `workflow_dispatch` button for on-demand runs. Fire URL and per-routine token live in repo secrets.
|
||||||
|
|
||||||
|
|||||||
@@ -1,10 +0,0 @@
|
|||||||
.git
|
|
||||||
.github
|
|
||||||
.gitignore
|
|
||||||
.dockerignore
|
|
||||||
Dockerfile
|
|
||||||
docker-compose*.yml
|
|
||||||
*.md
|
|
||||||
*_test.go
|
|
||||||
.idea
|
|
||||||
.vscode
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
# Required
|
|
||||||
ROUTINE_FIRE_URL=https://api.anthropic.com/v1/claude_code/routines/trig_xxx/fire
|
|
||||||
ROUTINE_FIRE_TOKEN=sk-ant-oat01-xxxxxxxx
|
|
||||||
@@ -1,58 +0,0 @@
|
|||||||
name: docker-publish
|
|
||||||
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches: [main]
|
|
||||||
tags: ['v*']
|
|
||||||
workflow_dispatch:
|
|
||||||
|
|
||||||
permissions:
|
|
||||||
contents: read
|
|
||||||
packages: write
|
|
||||||
id-token: write
|
|
||||||
|
|
||||||
env:
|
|
||||||
REGISTRY: ghcr.io
|
|
||||||
IMAGE_NAME: ${{ github.repository }}
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
build-and-push:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
|
|
||||||
- uses: docker/setup-qemu-action@v3
|
|
||||||
|
|
||||||
- uses: docker/setup-buildx-action@v3
|
|
||||||
|
|
||||||
- name: Log in to GHCR
|
|
||||||
uses: docker/login-action@v3
|
|
||||||
with:
|
|
||||||
registry: ${{ env.REGISTRY }}
|
|
||||||
username: ${{ github.actor }}
|
|
||||||
password: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
|
|
||||||
- name: Derive image metadata
|
|
||||||
id: meta
|
|
||||||
uses: docker/metadata-action@v5
|
|
||||||
with:
|
|
||||||
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
|
|
||||||
tags: |
|
|
||||||
type=ref,event=branch
|
|
||||||
type=ref,event=pr
|
|
||||||
type=semver,pattern={{version}}
|
|
||||||
type=semver,pattern={{major}}.{{minor}}
|
|
||||||
type=semver,pattern={{major}}
|
|
||||||
type=raw,value=latest,enable={{is_default_branch}}
|
|
||||||
type=sha,format=short,prefix=main-,enable={{is_default_branch}}
|
|
||||||
|
|
||||||
- name: Build and push
|
|
||||||
uses: docker/build-push-action@v5
|
|
||||||
with:
|
|
||||||
context: .
|
|
||||||
platforms: linux/amd64,linux/arm64
|
|
||||||
push: ${{ github.event_name != 'pull_request' }}
|
|
||||||
tags: ${{ steps.meta.outputs.tags }}
|
|
||||||
labels: ${{ steps.meta.outputs.labels }}
|
|
||||||
cache-from: type=gha
|
|
||||||
cache-to: type=gha,mode=max
|
|
||||||
-29
@@ -1,29 +0,0 @@
|
|||||||
name: test
|
|
||||||
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches: [main]
|
|
||||||
pull_request:
|
|
||||||
|
|
||||||
permissions:
|
|
||||||
contents: read
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
test:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
|
|
||||||
- uses: actions/setup-go@v5
|
|
||||||
with:
|
|
||||||
go-version: '1.22'
|
|
||||||
cache: true
|
|
||||||
|
|
||||||
- name: vet
|
|
||||||
run: go vet ./...
|
|
||||||
|
|
||||||
- name: test
|
|
||||||
run: go test -race -cover ./...
|
|
||||||
|
|
||||||
- name: build
|
|
||||||
run: go build ./...
|
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
# Build output
|
|
||||||
/claude-code-routine-cron
|
|
||||||
/dist/
|
|
||||||
*.exe
|
|
||||||
|
|
||||||
# Go test artifacts
|
|
||||||
*.test
|
|
||||||
*.out
|
|
||||||
coverage.txt
|
|
||||||
|
|
||||||
# IDE / OS
|
|
||||||
.idea/
|
|
||||||
.vscode/
|
|
||||||
.DS_Store
|
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
# syntax=docker/dockerfile:1.7
|
|
||||||
FROM --platform=$BUILDPLATFORM golang:1.22-alpine AS build
|
|
||||||
ARG TARGETOS
|
|
||||||
ARG TARGETARCH
|
|
||||||
WORKDIR /src
|
|
||||||
COPY go.mod go.sum ./
|
|
||||||
RUN go mod download
|
|
||||||
COPY . .
|
|
||||||
RUN CGO_ENABLED=0 GOOS=$TARGETOS GOARCH=$TARGETARCH \
|
|
||||||
go build -trimpath -ldflags="-s -w" -o /out/app .
|
|
||||||
|
|
||||||
FROM gcr.io/distroless/static-debian12:nonroot
|
|
||||||
COPY --from=build /out/app /app
|
|
||||||
ENTRYPOINT ["/app"]
|
|
||||||
@@ -1,202 +0,0 @@
|
|||||||
Apache License
|
|
||||||
Version 2.0, January 2004
|
|
||||||
http://www.apache.org/licenses/
|
|
||||||
|
|
||||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
||||||
|
|
||||||
1. Definitions.
|
|
||||||
|
|
||||||
"License" shall mean the terms and conditions for use, reproduction,
|
|
||||||
and distribution as defined by Sections 1 through 9 of this document.
|
|
||||||
|
|
||||||
"Licensor" shall mean the copyright owner or entity authorized by
|
|
||||||
the copyright owner that is granting the License.
|
|
||||||
|
|
||||||
"Legal Entity" shall mean the union of the acting entity and all
|
|
||||||
other entities that control, are controlled by, or are under common
|
|
||||||
control with that entity. For the purposes of this definition,
|
|
||||||
"control" means (i) the power, direct or indirect, to cause the
|
|
||||||
direction or management of such entity, whether by contract or
|
|
||||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
||||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
||||||
|
|
||||||
"You" (or "Your") shall mean an individual or Legal Entity
|
|
||||||
exercising permissions granted by this License.
|
|
||||||
|
|
||||||
"Source" form shall mean the preferred form for making modifications,
|
|
||||||
including but not limited to software source code, documentation
|
|
||||||
source, and configuration files.
|
|
||||||
|
|
||||||
"Object" form shall mean any form resulting from mechanical
|
|
||||||
transformation or translation of a Source form, including but
|
|
||||||
not limited to compiled object code, generated documentation,
|
|
||||||
and conversions to other media types.
|
|
||||||
|
|
||||||
"Work" shall mean the work of authorship, whether in Source or
|
|
||||||
Object form, made available under the License, as indicated by a
|
|
||||||
copyright notice that is included in or attached to the work
|
|
||||||
(an example is provided in the Appendix below).
|
|
||||||
|
|
||||||
"Derivative Works" shall mean any work, whether in Source or Object
|
|
||||||
form, that is based on (or derived from) the Work and for which the
|
|
||||||
editorial revisions, annotations, elaborations, or other modifications
|
|
||||||
represent, as a whole, an original work of authorship. For the purposes
|
|
||||||
of this License, Derivative Works shall not include works that remain
|
|
||||||
separable from, or merely link (or bind by name) to the interfaces of,
|
|
||||||
the Work and Derivative Works thereof.
|
|
||||||
|
|
||||||
"Contribution" shall mean any work of authorship, including
|
|
||||||
the original version of the Work and any modifications or additions
|
|
||||||
to that Work or Derivative Works thereof, that is intentionally
|
|
||||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
||||||
or by an individual or Legal Entity authorized to submit on behalf of
|
|
||||||
the copyright owner. For the purposes of this definition, "submitted"
|
|
||||||
means any form of electronic, verbal, or written communication sent
|
|
||||||
to the Licensor or its representatives, including but not limited to
|
|
||||||
communication on electronic mailing lists, source code control systems,
|
|
||||||
and issue tracking systems that are managed by, or on behalf of, the
|
|
||||||
Licensor for the purpose of discussing and improving the Work, but
|
|
||||||
excluding communication that is conspicuously marked or otherwise
|
|
||||||
designated in writing by the copyright owner as "Not a Contribution."
|
|
||||||
|
|
||||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
||||||
on behalf of whom a Contribution has been received by Licensor and
|
|
||||||
subsequently incorporated within the Work.
|
|
||||||
|
|
||||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
||||||
this License, each Contributor hereby grants to You a perpetual,
|
|
||||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
||||||
copyright license to reproduce, prepare Derivative Works of,
|
|
||||||
publicly display, publicly perform, sublicense, and distribute the
|
|
||||||
Work and such Derivative Works in Source or Object form.
|
|
||||||
|
|
||||||
3. Grant of Patent License. Subject to the terms and conditions of
|
|
||||||
this License, each Contributor hereby grants to You a perpetual,
|
|
||||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
||||||
(except as stated in this section) patent license to make, have made,
|
|
||||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
||||||
where such license applies only to those patent claims licensable
|
|
||||||
by such Contributor that are necessarily infringed by their
|
|
||||||
Contribution(s) alone or by combination of their Contribution(s)
|
|
||||||
with the Work to which such Contribution(s) was submitted. If You
|
|
||||||
institute patent litigation against any entity (including a
|
|
||||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
||||||
or a Contribution incorporated within the Work constitutes direct
|
|
||||||
or contributory patent infringement, then any patent licenses
|
|
||||||
granted to You under this License for that Work shall terminate
|
|
||||||
as of the date such litigation is filed.
|
|
||||||
|
|
||||||
4. Redistribution. You may reproduce and distribute copies of the
|
|
||||||
Work or Derivative Works thereof in any medium, with or without
|
|
||||||
modifications, and in Source or Object form, provided that You
|
|
||||||
meet the following conditions:
|
|
||||||
|
|
||||||
(a) You must give any other recipients of the Work or
|
|
||||||
Derivative Works a copy of this License; and
|
|
||||||
|
|
||||||
(b) You must cause any modified files to carry prominent notices
|
|
||||||
stating that You changed the files; and
|
|
||||||
|
|
||||||
(c) You must retain, in the Source form of any Derivative Works
|
|
||||||
that You distribute, all copyright, patent, trademark, and
|
|
||||||
attribution notices from the Source form of the Work,
|
|
||||||
excluding those notices that do not pertain to any part of
|
|
||||||
the Derivative Works; and
|
|
||||||
|
|
||||||
(d) If the Work includes a "NOTICE" text file as part of its
|
|
||||||
distribution, then any Derivative Works that You distribute must
|
|
||||||
include a readable copy of the attribution notices contained
|
|
||||||
within such NOTICE file, excluding those notices that do not
|
|
||||||
pertain to any part of the Derivative Works, in at least one
|
|
||||||
of the following places: within a NOTICE text file distributed
|
|
||||||
as part of the Derivative Works; within the Source form or
|
|
||||||
documentation, if provided along with the Derivative Works; or,
|
|
||||||
within a display generated by the Derivative Works, if and
|
|
||||||
wherever such third-party notices normally appear. The contents
|
|
||||||
of the NOTICE file are for informational purposes only and
|
|
||||||
do not modify the License. You may add Your own attribution
|
|
||||||
notices within Derivative Works that You distribute, alongside
|
|
||||||
or as an addendum to the NOTICE text from the Work, provided
|
|
||||||
that such additional attribution notices cannot be construed
|
|
||||||
as modifying the License.
|
|
||||||
|
|
||||||
You may add Your own copyright statement to Your modifications and
|
|
||||||
may provide additional or different license terms and conditions
|
|
||||||
for use, reproduction, or distribution of Your modifications, or
|
|
||||||
for any such Derivative Works as a whole, provided Your use,
|
|
||||||
reproduction, and distribution of the Work otherwise complies with
|
|
||||||
the conditions stated in this License.
|
|
||||||
|
|
||||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
||||||
any Contribution intentionally submitted for inclusion in the Work
|
|
||||||
by You to the Licensor shall be under the terms and conditions of
|
|
||||||
this License, without any additional terms or conditions.
|
|
||||||
Notwithstanding the above, nothing herein shall supersede or modify
|
|
||||||
the terms of any separate license agreement you may have executed
|
|
||||||
with Licensor regarding such Contributions.
|
|
||||||
|
|
||||||
6. Trademarks. This License does not grant permission to use the trade
|
|
||||||
names, trademarks, service marks, or product names of the Licensor,
|
|
||||||
except as required for reasonable and customary use in describing the
|
|
||||||
origin of the Work and reproducing the content of the NOTICE file.
|
|
||||||
|
|
||||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
||||||
agreed to in writing, Licensor provides the Work (and each
|
|
||||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
||||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
||||||
implied, including, without limitation, any warranties or conditions
|
|
||||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
||||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
||||||
appropriateness of using or redistributing the Work and assume any
|
|
||||||
risks associated with Your exercise of permissions under this License.
|
|
||||||
|
|
||||||
8. Limitation of Liability. In no event and under no legal theory,
|
|
||||||
whether in tort (including negligence), contract, or otherwise,
|
|
||||||
unless required by applicable law (such as deliberate and grossly
|
|
||||||
negligent acts) or agreed to in writing, shall any Contributor be
|
|
||||||
liable to You for damages, including any direct, indirect, special,
|
|
||||||
incidental, or consequential damages of any character arising as a
|
|
||||||
result of this License or out of the use or inability to use the
|
|
||||||
Work (including but not limited to damages for loss of goodwill,
|
|
||||||
work stoppage, computer failure or malfunction, or any and all
|
|
||||||
other commercial damages or losses), even if such Contributor
|
|
||||||
has been advised of the possibility of such damages.
|
|
||||||
|
|
||||||
9. Accepting Warranty or Additional Liability. While redistributing
|
|
||||||
the Work or Derivative Works thereof, You may choose to offer,
|
|
||||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
||||||
or other liability obligations and/or rights consistent with this
|
|
||||||
License. However, in accepting such obligations, You may act only
|
|
||||||
on Your own behalf and on Your sole responsibility, not on behalf
|
|
||||||
of any other Contributor, and only if You agree to indemnify,
|
|
||||||
defend, and hold each Contributor harmless for any liability
|
|
||||||
incurred by, or claims asserted against, such Contributor by reason
|
|
||||||
of your accepting any such warranty or additional liability.
|
|
||||||
|
|
||||||
END OF TERMS AND CONDITIONS
|
|
||||||
|
|
||||||
APPENDIX: How to apply the Apache License to your work.
|
|
||||||
|
|
||||||
To apply the Apache License to your work, attach the following
|
|
||||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
||||||
replaced with your own identifying information. (Don't include
|
|
||||||
the brackets!) The text should be enclosed in the appropriate
|
|
||||||
comment syntax for the file format. We also recommend that a
|
|
||||||
file or class name and description of purpose be included on the
|
|
||||||
same "printed page" as the copyright notice for easier
|
|
||||||
identification within third-party archives.
|
|
||||||
|
|
||||||
Copyright 2026 tiennm99
|
|
||||||
|
|
||||||
Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
you may not use this file except in compliance with the License.
|
|
||||||
You may obtain a copy of the License at
|
|
||||||
|
|
||||||
http://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
|
|
||||||
Unless required by applicable law or agreed to in writing, software
|
|
||||||
distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
See the License for the specific language governing permissions and
|
|
||||||
limitations under the License.
|
|
||||||
|
|
||||||
@@ -1,130 +0,0 @@
|
|||||||
# claude-code-routine-cron
|
|
||||||
|
|
||||||
Self-hosted Go daemon that fires a [Claude Code routine](https://code.claude.com/docs/en/routines) on a precise cron schedule via the [`/fire` API](https://platform.claude.com/docs/en/api/claude-code/routines-fire). Packaged as a multi-arch Docker image on GHCR.
|
|
||||||
|
|
||||||
> [!TIP]
|
|
||||||
> **Anthropic's routine editor now ships a built-in cron trigger** — that runs on Anthropic's infra, no setup. Use it first.
|
|
||||||
>
|
|
||||||
> This repo is for users who explicitly want **self-hosted scheduling**: precise timing (no GitHub Actions delays), behind-firewall, on-prem audit trail, or to integrate with their own infra.
|
|
||||||
|
|
||||||
## Why this vs `claude-code-routine-trigger`
|
|
||||||
|
|
||||||
| | [claude-code-routine-trigger](https://github.com/tiennm99/claude-code-routine-trigger) | **claude-code-routine-cron** (this repo) |
|
|
||||||
| ---------------- | -------------------------------------------------------------------------------------- | ---------------------------------------- |
|
|
||||||
| Runs on | GitHub Actions runners | your infra (Docker host, k8s, NAS, RPi) |
|
|
||||||
| Cost | free (within GitHub minutes) | minimal (your infra) |
|
|
||||||
| Cron precision | ±30 min – 2 h, can drop runs | sub-second |
|
|
||||||
| Setup | fork + 2 repo secrets | 2 env vars + cron + Docker |
|
|
||||||
| Secret storage | GitHub repo secrets | host env / Docker secrets / k8s Secret |
|
|
||||||
| Audit trail | GitHub Actions runs page | container stdout |
|
|
||||||
|
|
||||||
## Quickstart
|
|
||||||
|
|
||||||
```bash
|
|
||||||
docker run -d --name claude-routine \
|
|
||||||
--restart unless-stopped \
|
|
||||||
-e ROUTINE_FIRE_URL='https://api.anthropic.com/v1/claude_code/routines/trig_.../fire' \
|
|
||||||
-e ROUTINE_FIRE_TOKEN='sk-ant-oat01-...' \
|
|
||||||
-e CRON_SCHEDULE='0 9 * * *;0 18 * * *' \
|
|
||||||
-e TZ='Asia/Ho_Chi_Minh' \
|
|
||||||
ghcr.io/tiennm99/claude-code-routine-cron:latest
|
|
||||||
```
|
|
||||||
|
|
||||||
Tail logs:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
docker logs -f claude-routine
|
|
||||||
```
|
|
||||||
|
|
||||||
A successful fire logs a JSON line with `claude_code_session_url`. Open it to watch the run.
|
|
||||||
|
|
||||||
## Environment variables
|
|
||||||
|
|
||||||
| Name | Required | Default | Notes |
|
|
||||||
| -------------------- | :------: | ---------------------------------------- | ----- |
|
|
||||||
| `ROUTINE_FIRE_URL` | yes | — | Anthropic `/fire` endpoint. From routine editor → API trigger. |
|
|
||||||
| `ROUTINE_FIRE_TOKEN` | yes | — | `sk-ant-oat01-...` per-routine token. Shown once in the editor. |
|
|
||||||
| `CRON_SCHEDULE` | yes | — | One or more standard 5-field cron expressions. Split on `;` or newlines. |
|
|
||||||
| `TZ` | no | `UTC` | IANA tz name (`Asia/Ho_Chi_Minh`, `America/New_York`, …). Cron evaluates in this zone. |
|
|
||||||
| `TEXT_TEMPLATE` | no | `Scheduled trigger at {{.LocalTime}}` | Go [text/template](https://pkg.go.dev/text/template); see *Templates*. |
|
|
||||||
| `LOG_LEVEL` | no | `info` | `debug`, `info`, `warn`, `error`. |
|
|
||||||
|
|
||||||
Validation is fail-fast: missing required vars or malformed crons/timezones/templates cause the daemon to exit with a clear error before any HTTP traffic.
|
|
||||||
|
|
||||||
## Multiple schedules
|
|
||||||
|
|
||||||
Use `;` (or newlines, in YAML block scalars) to register multiple crons:
|
|
||||||
|
|
||||||
```yaml
|
|
||||||
environment:
|
|
||||||
CRON_SCHEDULE: |
|
|
||||||
0 9 * * *
|
|
||||||
0 13 * * *
|
|
||||||
0 18 * * *
|
|
||||||
```
|
|
||||||
|
|
||||||
Each schedule fires independently; all use the same `TEXT_TEMPLATE`, URL, and token.
|
|
||||||
|
|
||||||
## Templates
|
|
||||||
|
|
||||||
The `TEXT_TEMPLATE` env var is rendered as a Go `text/template` per fire with these variables:
|
|
||||||
|
|
||||||
| Var | Type | Example |
|
|
||||||
| ------------ | ----------- | -------------------------------- |
|
|
||||||
| `.Now` | `time.Time` | UTC time of the fire |
|
|
||||||
| `.LocalTime` | `string` | `2026-05-08 23:30 +07` |
|
|
||||||
| `.Cron` | `string` | `0 9 * * *` — the expression that fired |
|
|
||||||
|
|
||||||
Example:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
-e TEXT_TEMPLATE='Daily digest at {{.LocalTime}} (cron {{.Cron}})'
|
|
||||||
```
|
|
||||||
|
|
||||||
## docker-compose
|
|
||||||
|
|
||||||
See [`docker-compose.example.yml`](./docker-compose.example.yml) and [`.env.example`](./.env.example):
|
|
||||||
|
|
||||||
```bash
|
|
||||||
cp docker-compose.example.yml docker-compose.yml
|
|
||||||
cp .env.example .env # then edit secrets
|
|
||||||
docker compose up -d
|
|
||||||
```
|
|
||||||
|
|
||||||
## Security
|
|
||||||
|
|
||||||
- The token is **per-routine**: a leak only fires that one routine.
|
|
||||||
- Token never appears in logs (verified by tests).
|
|
||||||
- No retry on failure — each `/fire` POST creates a new session, retries would multiply sessions and burn quota.
|
|
||||||
- Image is `gcr.io/distroless/static-debian12:nonroot` — no shell, no package manager, runs as UID 65532.
|
|
||||||
- TLS to `api.anthropic.com` uses standard Go cert verification.
|
|
||||||
|
|
||||||
## Beta header
|
|
||||||
|
|
||||||
The request pins `anthropic-beta: experimental-cc-routine-2026-04-01`. When Anthropic ships a new dated beta, bump it via a new release. Older dated values keep working for a transition window per Anthropic's beta policy.
|
|
||||||
|
|
||||||
## Operational notes
|
|
||||||
|
|
||||||
- **Time accuracy**: cron correctness depends on the host clock. Run NTP / sync on the Docker host.
|
|
||||||
- **Restart policy**: use `--restart unless-stopped` (or k8s `Deployment`) — the daemon does not self-restart on panic.
|
|
||||||
- **Pin tags in production**: prefer `:vX.Y.Z` over `:latest`.
|
|
||||||
- **No idempotency**: avoid retry loops in upstream automation that POSTs the same alert twice.
|
|
||||||
|
|
||||||
## Build from source
|
|
||||||
|
|
||||||
```bash
|
|
||||||
git clone https://github.com/tiennm99/claude-code-routine-cron
|
|
||||||
cd claude-code-routine-cron
|
|
||||||
go build .
|
|
||||||
./claude-code-routine-cron # uses env vars from your shell
|
|
||||||
```
|
|
||||||
|
|
||||||
Tests:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
go test -race -cover ./...
|
|
||||||
```
|
|
||||||
|
|
||||||
## License
|
|
||||||
|
|
||||||
[Apache-2.0](./LICENSE)
|
|
||||||
@@ -1,104 +0,0 @@
|
|||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"os"
|
|
||||||
"regexp"
|
|
||||||
"strings"
|
|
||||||
"text/template"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/robfig/cron/v3"
|
|
||||||
)
|
|
||||||
|
|
||||||
const defaultTextTemplate = "Scheduled trigger at {{.LocalTime}}"
|
|
||||||
|
|
||||||
// Config is the validated runtime configuration assembled from env vars.
|
|
||||||
type Config struct {
|
|
||||||
FireURL string
|
|
||||||
Token string
|
|
||||||
Schedules []string
|
|
||||||
Location *time.Location
|
|
||||||
Template *template.Template
|
|
||||||
LogLevel string
|
|
||||||
}
|
|
||||||
|
|
||||||
// Load reads env vars and returns a fully validated Config or an error.
|
|
||||||
// All required vars must be present and all parsed values must pass validation.
|
|
||||||
func Load() (*Config, error) {
|
|
||||||
cfg := &Config{}
|
|
||||||
|
|
||||||
cfg.FireURL = strings.TrimSpace(os.Getenv("ROUTINE_FIRE_URL"))
|
|
||||||
if cfg.FireURL == "" {
|
|
||||||
return nil, errors.New("missing required env var ROUTINE_FIRE_URL")
|
|
||||||
}
|
|
||||||
|
|
||||||
cfg.Token = strings.TrimSpace(os.Getenv("ROUTINE_FIRE_TOKEN"))
|
|
||||||
if cfg.Token == "" {
|
|
||||||
return nil, errors.New("missing required env var ROUTINE_FIRE_TOKEN")
|
|
||||||
}
|
|
||||||
|
|
||||||
rawCron := os.Getenv("CRON_SCHEDULE")
|
|
||||||
schedules, err := parseSchedules(rawCron)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
cfg.Schedules = schedules
|
|
||||||
|
|
||||||
tz := strings.TrimSpace(os.Getenv("TZ"))
|
|
||||||
if tz == "" {
|
|
||||||
cfg.Location = time.UTC
|
|
||||||
} else {
|
|
||||||
loc, err := time.LoadLocation(tz)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("invalid TZ %q: %w", tz, err)
|
|
||||||
}
|
|
||||||
cfg.Location = loc
|
|
||||||
}
|
|
||||||
|
|
||||||
rawTpl := os.Getenv("TEXT_TEMPLATE")
|
|
||||||
if rawTpl == "" {
|
|
||||||
rawTpl = defaultTextTemplate
|
|
||||||
}
|
|
||||||
tpl, err := template.New("text").Parse(rawTpl)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("invalid TEXT_TEMPLATE: %w", err)
|
|
||||||
}
|
|
||||||
cfg.Template = tpl
|
|
||||||
|
|
||||||
cfg.LogLevel = strings.TrimSpace(os.Getenv("LOG_LEVEL"))
|
|
||||||
if cfg.LogLevel == "" {
|
|
||||||
cfg.LogLevel = "info"
|
|
||||||
}
|
|
||||||
|
|
||||||
return cfg, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
var scheduleSeparators = regexp.MustCompile(`[;\n]+`)
|
|
||||||
|
|
||||||
// parseSchedules splits CRON_SCHEDULE on `;` or newlines, trims, drops empties,
|
|
||||||
// and validates each expression against the standard 5-field parser.
|
|
||||||
func parseSchedules(raw string) ([]string, error) {
|
|
||||||
if strings.TrimSpace(raw) == "" {
|
|
||||||
return nil, errors.New("missing required env var CRON_SCHEDULE")
|
|
||||||
}
|
|
||||||
parts := scheduleSeparators.Split(raw, -1)
|
|
||||||
parser := cron.NewParser(cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow)
|
|
||||||
|
|
||||||
out := make([]string, 0, len(parts))
|
|
||||||
for _, p := range parts {
|
|
||||||
s := strings.TrimSpace(p)
|
|
||||||
if s == "" {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if _, err := parser.Parse(s); err != nil {
|
|
||||||
return nil, fmt.Errorf("invalid cron %q: %w", s, err)
|
|
||||||
}
|
|
||||||
out = append(out, s)
|
|
||||||
}
|
|
||||||
if len(out) == 0 {
|
|
||||||
return nil, errors.New("CRON_SCHEDULE has no non-empty expressions")
|
|
||||||
}
|
|
||||||
return out, nil
|
|
||||||
}
|
|
||||||
@@ -1,215 +0,0 @@
|
|||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"strings"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
func clearEnv(t *testing.T) {
|
|
||||||
t.Helper()
|
|
||||||
for _, k := range []string{"ROUTINE_FIRE_URL", "ROUTINE_FIRE_TOKEN", "CRON_SCHEDULE", "TZ", "TEXT_TEMPLATE", "LOG_LEVEL"} {
|
|
||||||
t.Setenv(k, "")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func setBaseEnv(t *testing.T) {
|
|
||||||
t.Helper()
|
|
||||||
t.Setenv("ROUTINE_FIRE_URL", "https://example.test/fire")
|
|
||||||
t.Setenv("ROUTINE_FIRE_TOKEN", "tok")
|
|
||||||
t.Setenv("CRON_SCHEDULE", "0 9 * * *")
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestLoad_Happy(t *testing.T) {
|
|
||||||
clearEnv(t)
|
|
||||||
setBaseEnv(t)
|
|
||||||
|
|
||||||
cfg, err := Load()
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("unexpected error: %v", err)
|
|
||||||
}
|
|
||||||
if len(cfg.Schedules) != 1 || cfg.Schedules[0] != "0 9 * * *" {
|
|
||||||
t.Fatalf("schedules = %v", cfg.Schedules)
|
|
||||||
}
|
|
||||||
if cfg.Location != time.UTC {
|
|
||||||
t.Fatalf("default tz should be UTC, got %v", cfg.Location)
|
|
||||||
}
|
|
||||||
if cfg.LogLevel != "info" {
|
|
||||||
t.Fatalf("default log level should be info, got %q", cfg.LogLevel)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestLoad_MultiCronSemicolon(t *testing.T) {
|
|
||||||
clearEnv(t)
|
|
||||||
setBaseEnv(t)
|
|
||||||
t.Setenv("CRON_SCHEDULE", "0 17 * * *;0 22 * * *")
|
|
||||||
|
|
||||||
cfg, err := Load()
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("unexpected error: %v", err)
|
|
||||||
}
|
|
||||||
if len(cfg.Schedules) != 2 {
|
|
||||||
t.Fatalf("want 2, got %d: %v", len(cfg.Schedules), cfg.Schedules)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestLoad_MultiCronNewline(t *testing.T) {
|
|
||||||
clearEnv(t)
|
|
||||||
setBaseEnv(t)
|
|
||||||
t.Setenv("CRON_SCHEDULE", "0 17 * * *\n0 22 * * *")
|
|
||||||
|
|
||||||
cfg, err := Load()
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("unexpected error: %v", err)
|
|
||||||
}
|
|
||||||
if len(cfg.Schedules) != 2 {
|
|
||||||
t.Fatalf("want 2, got %d: %v", len(cfg.Schedules), cfg.Schedules)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestLoad_MixedSeparatorsAndWhitespace(t *testing.T) {
|
|
||||||
clearEnv(t)
|
|
||||||
setBaseEnv(t)
|
|
||||||
t.Setenv("CRON_SCHEDULE", " 0 17 * * * ;\n 0 22 * * * ;;\n")
|
|
||||||
|
|
||||||
cfg, err := Load()
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("unexpected error: %v", err)
|
|
||||||
}
|
|
||||||
if len(cfg.Schedules) != 2 {
|
|
||||||
t.Fatalf("want 2 trimmed schedules, got %v", cfg.Schedules)
|
|
||||||
}
|
|
||||||
if cfg.Schedules[0] != "0 17 * * *" || cfg.Schedules[1] != "0 22 * * *" {
|
|
||||||
t.Fatalf("unexpected trimmed values: %v", cfg.Schedules)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestLoad_MissingFireURL(t *testing.T) {
|
|
||||||
clearEnv(t)
|
|
||||||
t.Setenv("ROUTINE_FIRE_TOKEN", "tok")
|
|
||||||
t.Setenv("CRON_SCHEDULE", "0 9 * * *")
|
|
||||||
|
|
||||||
_, err := Load()
|
|
||||||
if err == nil || !strings.Contains(err.Error(), "ROUTINE_FIRE_URL") {
|
|
||||||
t.Fatalf("want missing url error, got %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestLoad_MissingToken(t *testing.T) {
|
|
||||||
clearEnv(t)
|
|
||||||
t.Setenv("ROUTINE_FIRE_URL", "https://example.test/fire")
|
|
||||||
t.Setenv("CRON_SCHEDULE", "0 9 * * *")
|
|
||||||
|
|
||||||
_, err := Load()
|
|
||||||
if err == nil || !strings.Contains(err.Error(), "ROUTINE_FIRE_TOKEN") {
|
|
||||||
t.Fatalf("want missing token error, got %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestLoad_EmptyCron(t *testing.T) {
|
|
||||||
clearEnv(t)
|
|
||||||
t.Setenv("ROUTINE_FIRE_URL", "https://example.test/fire")
|
|
||||||
t.Setenv("ROUTINE_FIRE_TOKEN", "tok")
|
|
||||||
t.Setenv("CRON_SCHEDULE", "")
|
|
||||||
|
|
||||||
_, err := Load()
|
|
||||||
if err == nil || !strings.Contains(err.Error(), "CRON_SCHEDULE") {
|
|
||||||
t.Fatalf("want missing cron error, got %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestLoad_InvalidCron(t *testing.T) {
|
|
||||||
clearEnv(t)
|
|
||||||
setBaseEnv(t)
|
|
||||||
t.Setenv("CRON_SCHEDULE", "not-a-cron")
|
|
||||||
|
|
||||||
_, err := Load()
|
|
||||||
if err == nil || !strings.Contains(err.Error(), "invalid cron") {
|
|
||||||
t.Fatalf("want invalid cron error, got %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestLoad_InvalidTZ(t *testing.T) {
|
|
||||||
clearEnv(t)
|
|
||||||
setBaseEnv(t)
|
|
||||||
t.Setenv("TZ", "Atlantis/Lost")
|
|
||||||
|
|
||||||
_, err := Load()
|
|
||||||
if err == nil || !strings.Contains(err.Error(), "invalid TZ") {
|
|
||||||
t.Fatalf("want invalid TZ error, got %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestLoad_DefaultTemplate(t *testing.T) {
|
|
||||||
clearEnv(t)
|
|
||||||
setBaseEnv(t)
|
|
||||||
|
|
||||||
cfg, err := Load()
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("unexpected error: %v", err)
|
|
||||||
}
|
|
||||||
out, err := renderTemplate(cfg, time.Date(2026, 5, 8, 12, 0, 0, 0, time.UTC), "0 9 * * *")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("render: %v", err)
|
|
||||||
}
|
|
||||||
if !strings.HasPrefix(out, "Scheduled trigger at ") {
|
|
||||||
t.Fatalf("default template output unexpected: %q", out)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestLoad_CustomTemplate(t *testing.T) {
|
|
||||||
clearEnv(t)
|
|
||||||
setBaseEnv(t)
|
|
||||||
t.Setenv("TEXT_TEMPLATE", "hi {{.Cron}}")
|
|
||||||
|
|
||||||
cfg, err := Load()
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("unexpected error: %v", err)
|
|
||||||
}
|
|
||||||
out, err := renderTemplate(cfg, time.Now(), "0 9 * * *")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("render: %v", err)
|
|
||||||
}
|
|
||||||
if out != "hi 0 9 * * *" {
|
|
||||||
t.Fatalf("custom template output: %q", out)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestLoad_InvalidTemplate(t *testing.T) {
|
|
||||||
clearEnv(t)
|
|
||||||
setBaseEnv(t)
|
|
||||||
t.Setenv("TEXT_TEMPLATE", "{{.broken")
|
|
||||||
|
|
||||||
_, err := Load()
|
|
||||||
if err == nil || !strings.Contains(err.Error(), "invalid TEXT_TEMPLATE") {
|
|
||||||
t.Fatalf("want invalid template error, got %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestLoad_LogLevelDefault(t *testing.T) {
|
|
||||||
clearEnv(t)
|
|
||||||
setBaseEnv(t)
|
|
||||||
|
|
||||||
cfg, err := Load()
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("unexpected error: %v", err)
|
|
||||||
}
|
|
||||||
if cfg.LogLevel != "info" {
|
|
||||||
t.Fatalf("got %q", cfg.LogLevel)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// renderTemplate runs cfg.Template with the documented vars; mirror of
|
|
||||||
// FireClient.renderText for test isolation.
|
|
||||||
func renderTemplate(cfg *Config, now time.Time, expr string) (string, error) {
|
|
||||||
data := map[string]any{
|
|
||||||
"Now": now,
|
|
||||||
"LocalTime": now.In(cfg.Location).Format("2006-01-02 15:04 MST"),
|
|
||||||
"Cron": expr,
|
|
||||||
}
|
|
||||||
var sb strings.Builder
|
|
||||||
if err := cfg.Template.Execute(&sb, data); err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
return sb.String(), nil
|
|
||||||
}
|
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
services:
|
|
||||||
claude-routine:
|
|
||||||
image: ghcr.io/tiennm99/claude-code-routine-cron:latest
|
|
||||||
restart: unless-stopped
|
|
||||||
environment:
|
|
||||||
ROUTINE_FIRE_URL: ${ROUTINE_FIRE_URL}
|
|
||||||
ROUTINE_FIRE_TOKEN: ${ROUTINE_FIRE_TOKEN}
|
|
||||||
CRON_SCHEDULE: |
|
|
||||||
0 9 * * *
|
|
||||||
0 18 * * *
|
|
||||||
TZ: Asia/Ho_Chi_Minh
|
|
||||||
LOG_LEVEL: info
|
|
||||||
# Optional: override the default text sent to the routine.
|
|
||||||
# TEXT_TEMPLATE: "Daily digest at {{.LocalTime}} (cron {{.Cron}})"
|
|
||||||
@@ -1,118 +0,0 @@
|
|||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"context"
|
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
"log/slog"
|
|
||||||
"net/http"
|
|
||||||
"text/template"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
headerVersion = "2023-06-01"
|
|
||||||
headerBeta = "experimental-cc-routine-2026-04-01"
|
|
||||||
)
|
|
||||||
|
|
||||||
// FireClient POSTs to the Anthropic /fire endpoint with the headers and body
|
|
||||||
// shape required by the Claude Code routines beta. Each call creates a new
|
|
||||||
// session; the daemon never retries on failure.
|
|
||||||
type FireClient struct {
|
|
||||||
URL string
|
|
||||||
Token string
|
|
||||||
HTTP *http.Client
|
|
||||||
Template *template.Template
|
|
||||||
TZ *time.Location
|
|
||||||
Log *slog.Logger
|
|
||||||
NowFunc func() time.Time // overridable for tests; defaults to time.Now
|
|
||||||
}
|
|
||||||
|
|
||||||
type fireRequest struct {
|
|
||||||
Text string `json:"text"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type fireResponse struct {
|
|
||||||
Type string `json:"type"`
|
|
||||||
ClaudeCodeSessionID string `json:"claude_code_session_id"`
|
|
||||||
ClaudeCodeSessionURL string `json:"claude_code_session_url"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fire renders the text template, POSTs to the routine /fire endpoint, and
|
|
||||||
// logs the outcome. Returns nil on transport-level success regardless of HTTP
|
|
||||||
// status — non-2xx is logged at error level so the daemon stays up.
|
|
||||||
// Returns a non-nil error only for unrecoverable client-side problems
|
|
||||||
// (template render failure or request build failure).
|
|
||||||
func (c *FireClient) Fire(ctx context.Context, cronExpr string) error {
|
|
||||||
now := c.now()
|
|
||||||
text, err := c.renderText(now, cronExpr)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("render text: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
body, err := json.Marshal(fireRequest{Text: text})
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("marshal request: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.URL, bytes.NewReader(body))
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("build request: %w", err)
|
|
||||||
}
|
|
||||||
req.Header.Set("Authorization", "Bearer "+c.Token)
|
|
||||||
req.Header.Set("anthropic-version", headerVersion)
|
|
||||||
req.Header.Set("anthropic-beta", headerBeta)
|
|
||||||
req.Header.Set("Content-Type", "application/json")
|
|
||||||
|
|
||||||
resp, err := c.HTTP.Do(req)
|
|
||||||
if err != nil {
|
|
||||||
c.Log.Error("fire request failed", "cron", cronExpr, "err", err.Error())
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
defer resp.Body.Close()
|
|
||||||
|
|
||||||
respBody, _ := io.ReadAll(resp.Body)
|
|
||||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
|
||||||
c.Log.Error("fire non-2xx response",
|
|
||||||
"cron", cronExpr,
|
|
||||||
"status", resp.StatusCode,
|
|
||||||
"body", string(respBody))
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
var fr fireResponse
|
|
||||||
if err := json.Unmarshal(respBody, &fr); err != nil {
|
|
||||||
c.Log.Warn("fire 2xx but body unparseable",
|
|
||||||
"cron", cronExpr,
|
|
||||||
"status", resp.StatusCode,
|
|
||||||
"body", string(respBody))
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
c.Log.Info("fire ok",
|
|
||||||
"cron", cronExpr,
|
|
||||||
"session_url", fr.ClaudeCodeSessionURL,
|
|
||||||
"session_id", fr.ClaudeCodeSessionID)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *FireClient) now() time.Time {
|
|
||||||
if c.NowFunc != nil {
|
|
||||||
return c.NowFunc()
|
|
||||||
}
|
|
||||||
return time.Now()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *FireClient) renderText(now time.Time, cronExpr string) (string, error) {
|
|
||||||
data := map[string]any{
|
|
||||||
"Now": now,
|
|
||||||
"LocalTime": now.In(c.TZ).Format("2006-01-02 15:04 MST"),
|
|
||||||
"Cron": cronExpr,
|
|
||||||
}
|
|
||||||
var buf bytes.Buffer
|
|
||||||
if err := c.Template.Execute(&buf, data); err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
return buf.String(), nil
|
|
||||||
}
|
|
||||||
@@ -1,174 +0,0 @@
|
|||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"context"
|
|
||||||
"encoding/json"
|
|
||||||
"io"
|
|
||||||
"log/slog"
|
|
||||||
"net/http"
|
|
||||||
"net/http/httptest"
|
|
||||||
"strings"
|
|
||||||
"testing"
|
|
||||||
"text/template"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
func captureLogs() (*slog.Logger, *bytes.Buffer) {
|
|
||||||
var buf bytes.Buffer
|
|
||||||
h := slog.NewJSONHandler(&buf, &slog.HandlerOptions{Level: slog.LevelDebug})
|
|
||||||
return slog.New(h), &buf
|
|
||||||
}
|
|
||||||
|
|
||||||
func mustTemplate(t *testing.T, raw string) *template.Template {
|
|
||||||
t.Helper()
|
|
||||||
tpl, err := template.New("t").Parse(raw)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("template parse: %v", err)
|
|
||||||
}
|
|
||||||
return tpl
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestFire_HappyPath(t *testing.T) {
|
|
||||||
var gotMethod, gotAuth, gotVersion, gotBeta, gotContentType string
|
|
||||||
var gotBody []byte
|
|
||||||
|
|
||||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
gotMethod = r.Method
|
|
||||||
gotAuth = r.Header.Get("Authorization")
|
|
||||||
gotVersion = r.Header.Get("anthropic-version")
|
|
||||||
gotBeta = r.Header.Get("anthropic-beta")
|
|
||||||
gotContentType = r.Header.Get("Content-Type")
|
|
||||||
gotBody, _ = io.ReadAll(r.Body)
|
|
||||||
_, _ = w.Write([]byte(`{"type":"routine_fire","claude_code_session_id":"sess_1","claude_code_session_url":"https://claude.ai/code/sess_1"}`))
|
|
||||||
}))
|
|
||||||
defer srv.Close()
|
|
||||||
|
|
||||||
logger, logbuf := captureLogs()
|
|
||||||
c := &FireClient{
|
|
||||||
URL: srv.URL,
|
|
||||||
Token: "tok",
|
|
||||||
HTTP: &http.Client{Timeout: 5 * time.Second},
|
|
||||||
Template: mustTemplate(t, "fire {{.Cron}}"),
|
|
||||||
TZ: time.UTC,
|
|
||||||
Log: logger,
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := c.Fire(context.Background(), "0 9 * * *"); err != nil {
|
|
||||||
t.Fatalf("Fire returned error: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if gotMethod != http.MethodPost {
|
|
||||||
t.Errorf("method = %q", gotMethod)
|
|
||||||
}
|
|
||||||
if gotAuth != "Bearer tok" {
|
|
||||||
t.Errorf("auth = %q", gotAuth)
|
|
||||||
}
|
|
||||||
if gotVersion != headerVersion {
|
|
||||||
t.Errorf("anthropic-version = %q", gotVersion)
|
|
||||||
}
|
|
||||||
if gotBeta != headerBeta {
|
|
||||||
t.Errorf("anthropic-beta = %q", gotBeta)
|
|
||||||
}
|
|
||||||
if gotContentType != "application/json" {
|
|
||||||
t.Errorf("content-type = %q", gotContentType)
|
|
||||||
}
|
|
||||||
|
|
||||||
var body fireRequest
|
|
||||||
if err := json.Unmarshal(gotBody, &body); err != nil {
|
|
||||||
t.Fatalf("body unmarshal: %v", err)
|
|
||||||
}
|
|
||||||
if body.Text != "fire 0 9 * * *" {
|
|
||||||
t.Errorf("body.text = %q", body.Text)
|
|
||||||
}
|
|
||||||
|
|
||||||
if !strings.Contains(logbuf.String(), "fire ok") {
|
|
||||||
t.Errorf("expected 'fire ok' log, got: %s", logbuf.String())
|
|
||||||
}
|
|
||||||
if !strings.Contains(logbuf.String(), "https://claude.ai/code/sess_1") {
|
|
||||||
t.Errorf("expected session url in log, got: %s", logbuf.String())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestFire_NonOK(t *testing.T) {
|
|
||||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
w.WriteHeader(http.StatusUnauthorized)
|
|
||||||
_, _ = w.Write([]byte(`{"error":"unauthorized"}`))
|
|
||||||
}))
|
|
||||||
defer srv.Close()
|
|
||||||
|
|
||||||
logger, logbuf := captureLogs()
|
|
||||||
c := &FireClient{
|
|
||||||
URL: srv.URL,
|
|
||||||
Token: "tok",
|
|
||||||
HTTP: &http.Client{Timeout: 5 * time.Second},
|
|
||||||
Template: mustTemplate(t, "x"),
|
|
||||||
TZ: time.UTC,
|
|
||||||
Log: logger,
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := c.Fire(context.Background(), "0 9 * * *"); err != nil {
|
|
||||||
t.Fatalf("Fire should swallow non-2xx, got error: %v", err)
|
|
||||||
}
|
|
||||||
out := logbuf.String()
|
|
||||||
if !strings.Contains(out, "non-2xx") {
|
|
||||||
t.Errorf("expected non-2xx log, got: %s", out)
|
|
||||||
}
|
|
||||||
if !strings.Contains(out, "401") {
|
|
||||||
t.Errorf("expected status 401 in log, got: %s", out)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestFire_NetworkError(t *testing.T) {
|
|
||||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
|
|
||||||
srv.Close() // close immediately so requests fail
|
|
||||||
|
|
||||||
logger, logbuf := captureLogs()
|
|
||||||
c := &FireClient{
|
|
||||||
URL: srv.URL,
|
|
||||||
Token: "tok",
|
|
||||||
HTTP: &http.Client{Timeout: 1 * time.Second},
|
|
||||||
Template: mustTemplate(t, "x"),
|
|
||||||
TZ: time.UTC,
|
|
||||||
Log: logger,
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := c.Fire(context.Background(), "0 9 * * *"); err != nil {
|
|
||||||
t.Fatalf("Fire should swallow network error, got: %v", err)
|
|
||||||
}
|
|
||||||
if !strings.Contains(logbuf.String(), "fire request failed") {
|
|
||||||
t.Errorf("expected request-failed log, got: %s", logbuf.String())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestFire_TemplateUsesNowFunc(t *testing.T) {
|
|
||||||
var gotBody []byte
|
|
||||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
gotBody, _ = io.ReadAll(r.Body)
|
|
||||||
_, _ = w.Write([]byte(`{}`))
|
|
||||||
}))
|
|
||||||
defer srv.Close()
|
|
||||||
|
|
||||||
fixed := time.Date(2026, 5, 8, 23, 30, 0, 0, time.UTC)
|
|
||||||
logger, _ := captureLogs()
|
|
||||||
c := &FireClient{
|
|
||||||
URL: srv.URL,
|
|
||||||
Token: "tok",
|
|
||||||
HTTP: &http.Client{Timeout: 5 * time.Second},
|
|
||||||
Template: mustTemplate(t, "{{.LocalTime}}"),
|
|
||||||
TZ: time.UTC,
|
|
||||||
Log: logger,
|
|
||||||
NowFunc: func() time.Time { return fixed },
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := c.Fire(context.Background(), "0 9 * * *"); err != nil {
|
|
||||||
t.Fatalf("Fire: %v", err)
|
|
||||||
}
|
|
||||||
var body fireRequest
|
|
||||||
if err := json.Unmarshal(gotBody, &body); err != nil {
|
|
||||||
t.Fatalf("unmarshal: %v", err)
|
|
||||||
}
|
|
||||||
if body.Text != "2026-05-08 23:30 UTC" {
|
|
||||||
t.Errorf("body.text = %q", body.Text)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
module github.com/tiennm99/claude-code-routine-cron
|
|
||||||
|
|
||||||
go 1.22
|
|
||||||
|
|
||||||
require github.com/robfig/cron/v3 v3.0.1
|
|
||||||
@@ -1,2 +0,0 @@
|
|||||||
github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs=
|
|
||||||
github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro=
|
|
||||||
@@ -1,40 +0,0 @@
|
|||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"log/slog"
|
|
||||||
"os"
|
|
||||||
"strings"
|
|
||||||
)
|
|
||||||
|
|
||||||
// newLogger builds a JSON slog logger writing to stdout at the given level.
|
|
||||||
// Unknown levels fall back to info and emit a warning on the new logger.
|
|
||||||
func newLogger(level string) *slog.Logger {
|
|
||||||
lvl := parseLevel(level)
|
|
||||||
h := slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: lvl})
|
|
||||||
l := slog.New(h)
|
|
||||||
if !knownLevel(level) {
|
|
||||||
l.Warn("unknown LOG_LEVEL, using info", "got", level)
|
|
||||||
}
|
|
||||||
return l
|
|
||||||
}
|
|
||||||
|
|
||||||
func parseLevel(s string) slog.Level {
|
|
||||||
switch strings.ToLower(strings.TrimSpace(s)) {
|
|
||||||
case "debug":
|
|
||||||
return slog.LevelDebug
|
|
||||||
case "warn", "warning":
|
|
||||||
return slog.LevelWarn
|
|
||||||
case "error":
|
|
||||||
return slog.LevelError
|
|
||||||
default:
|
|
||||||
return slog.LevelInfo
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func knownLevel(s string) bool {
|
|
||||||
switch strings.ToLower(strings.TrimSpace(s)) {
|
|
||||||
case "", "info", "debug", "warn", "warning", "error":
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
@@ -1,61 +0,0 @@
|
|||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"log"
|
|
||||||
"log/slog"
|
|
||||||
"net/http"
|
|
||||||
"os"
|
|
||||||
"os/signal"
|
|
||||||
"syscall"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
httpClientTimeout = 30 * time.Second
|
|
||||||
httpFireTimeout = 30 * time.Second
|
|
||||||
shutdownTimeout = 35 * time.Second
|
|
||||||
)
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
cfg, err := Load()
|
|
||||||
if err != nil {
|
|
||||||
log.Fatalf("config: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
logger := newLogger(cfg.LogLevel)
|
|
||||||
slog.SetDefault(logger)
|
|
||||||
|
|
||||||
fire := &FireClient{
|
|
||||||
URL: cfg.FireURL,
|
|
||||||
Token: cfg.Token,
|
|
||||||
HTTP: &http.Client{Timeout: httpClientTimeout},
|
|
||||||
Template: cfg.Template,
|
|
||||||
TZ: cfg.Location,
|
|
||||||
Log: logger,
|
|
||||||
}
|
|
||||||
|
|
||||||
sched, err := NewScheduler(cfg, fire, logger)
|
|
||||||
if err != nil {
|
|
||||||
logger.Error("scheduler init failed", "err", err.Error())
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
|
||||||
defer cancel()
|
|
||||||
|
|
||||||
sched.Start()
|
|
||||||
logger.Info("started",
|
|
||||||
"schedules", cfg.Schedules,
|
|
||||||
"tz", cfg.Location.String(),
|
|
||||||
"entries", sched.EntryCount(),
|
|
||||||
)
|
|
||||||
|
|
||||||
<-ctx.Done()
|
|
||||||
logger.Info("shutting down")
|
|
||||||
|
|
||||||
stopCtx, stopCancel := context.WithTimeout(context.Background(), shutdownTimeout)
|
|
||||||
defer stopCancel()
|
|
||||||
sched.Stop(stopCtx)
|
|
||||||
logger.Info("stopped cleanly")
|
|
||||||
}
|
|
||||||
@@ -1,60 +0,0 @@
|
|||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"fmt"
|
|
||||||
"log/slog"
|
|
||||||
|
|
||||||
"github.com/robfig/cron/v3"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Scheduler wires cron schedules to FireClient invocations.
|
|
||||||
type Scheduler struct {
|
|
||||||
cron *cron.Cron
|
|
||||||
fire *FireClient
|
|
||||||
log *slog.Logger
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewScheduler builds a Scheduler with all schedules registered. Returns an
|
|
||||||
// error if any registration fails (defensive — config.go already validates
|
|
||||||
// expressions, but the cron library may have stricter rules at AddFunc time).
|
|
||||||
func NewScheduler(cfg *Config, fire *FireClient, log *slog.Logger) (*Scheduler, error) {
|
|
||||||
c := cron.New(cron.WithLocation(cfg.Location))
|
|
||||||
s := &Scheduler{cron: c, fire: fire, log: log}
|
|
||||||
|
|
||||||
for _, expr := range cfg.Schedules {
|
|
||||||
expr := expr
|
|
||||||
_, err := c.AddFunc(expr, func() {
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), httpFireTimeout)
|
|
||||||
defer cancel()
|
|
||||||
if err := fire.Fire(ctx, expr); err != nil {
|
|
||||||
log.Error("fire returned error", "cron", expr, "err", err.Error())
|
|
||||||
}
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("register cron %q: %w", expr, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return s, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Start the underlying cron scheduler. Non-blocking.
|
|
||||||
func (s *Scheduler) Start() {
|
|
||||||
s.cron.Start()
|
|
||||||
}
|
|
||||||
|
|
||||||
// Stop the scheduler and wait for in-flight tasks to finish or for the
|
|
||||||
// supplied context to be cancelled, whichever comes first.
|
|
||||||
func (s *Scheduler) Stop(ctx context.Context) {
|
|
||||||
stopped := s.cron.Stop().Done()
|
|
||||||
select {
|
|
||||||
case <-stopped:
|
|
||||||
case <-ctx.Done():
|
|
||||||
s.log.Warn("shutdown deadline reached before all fires completed")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// EntryCount exposes the number of registered schedules for tests/diagnostics.
|
|
||||||
func (s *Scheduler) EntryCount() int {
|
|
||||||
return len(s.cron.Entries())
|
|
||||||
}
|
|
||||||
@@ -1,104 +0,0 @@
|
|||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"net/http"
|
|
||||||
"net/http/httptest"
|
|
||||||
"testing"
|
|
||||||
"text/template"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestScheduler_RegistersAllEntries(t *testing.T) {
|
|
||||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
_, _ = w.Write([]byte(`{}`))
|
|
||||||
}))
|
|
||||||
defer srv.Close()
|
|
||||||
|
|
||||||
tpl, _ := template.New("t").Parse("x")
|
|
||||||
cfg := &Config{
|
|
||||||
FireURL: srv.URL,
|
|
||||||
Token: "tok",
|
|
||||||
Schedules: []string{"0 17 * * *", "0 22 * * *", "*/5 * * * *"},
|
|
||||||
Location: time.UTC,
|
|
||||||
Template: tpl,
|
|
||||||
LogLevel: "info",
|
|
||||||
}
|
|
||||||
logger, _ := captureLogs()
|
|
||||||
fire := &FireClient{
|
|
||||||
URL: srv.URL,
|
|
||||||
Token: "tok",
|
|
||||||
HTTP: &http.Client{Timeout: 1 * time.Second},
|
|
||||||
Template: tpl,
|
|
||||||
TZ: time.UTC,
|
|
||||||
Log: logger,
|
|
||||||
}
|
|
||||||
|
|
||||||
s, err := NewScheduler(cfg, fire, logger)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("NewScheduler: %v", err)
|
|
||||||
}
|
|
||||||
if got := s.EntryCount(); got != 3 {
|
|
||||||
t.Fatalf("EntryCount = %d, want 3", got)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestScheduler_StartStop(t *testing.T) {
|
|
||||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
_, _ = w.Write([]byte(`{}`))
|
|
||||||
}))
|
|
||||||
defer srv.Close()
|
|
||||||
|
|
||||||
tpl, _ := template.New("t").Parse("x")
|
|
||||||
cfg := &Config{
|
|
||||||
FireURL: srv.URL,
|
|
||||||
Token: "tok",
|
|
||||||
Schedules: []string{"0 17 * * *"},
|
|
||||||
Location: time.UTC,
|
|
||||||
Template: tpl,
|
|
||||||
LogLevel: "info",
|
|
||||||
}
|
|
||||||
logger, _ := captureLogs()
|
|
||||||
fire := &FireClient{
|
|
||||||
URL: srv.URL,
|
|
||||||
Token: "tok",
|
|
||||||
HTTP: &http.Client{Timeout: 1 * time.Second},
|
|
||||||
Template: tpl,
|
|
||||||
TZ: time.UTC,
|
|
||||||
Log: logger,
|
|
||||||
}
|
|
||||||
|
|
||||||
s, err := NewScheduler(cfg, fire, logger)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("NewScheduler: %v", err)
|
|
||||||
}
|
|
||||||
s.Start()
|
|
||||||
|
|
||||||
stopCtx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
|
||||||
defer cancel()
|
|
||||||
done := make(chan struct{})
|
|
||||||
go func() {
|
|
||||||
s.Stop(stopCtx)
|
|
||||||
close(done)
|
|
||||||
}()
|
|
||||||
select {
|
|
||||||
case <-done:
|
|
||||||
case <-time.After(3 * time.Second):
|
|
||||||
t.Fatal("Stop did not return within 3s")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestNewLogger_UnknownLevelFallsBackToInfo(t *testing.T) {
|
|
||||||
l := newLogger("zoinks")
|
|
||||||
if l == nil {
|
|
||||||
t.Fatal("logger is nil")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestNewLogger_KnownLevels(t *testing.T) {
|
|
||||||
for _, lvl := range []string{"", "debug", "info", "warn", "warning", "error", "ERROR", " Debug "} {
|
|
||||||
if l := newLogger(lvl); l == nil {
|
|
||||||
t.Fatalf("nil logger for %q", lvl)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Reference in new issue
Block a user