Refactor to Go standards; add print queue and own ESC/POS library
CI / Lint, test and scan (push) Successful in 1m41s
CI / Lint, test and scan (push) Successful in 1m41s
Restructure the daemon to follow the project's Go coding standards and
expand its features.
Layout and tooling
- cmd/uberbringer/main.go is now thin; all logic lives under internal/.
- Module path is git.anomalous.dev/57_Wolve/uberbringer, go 1.26, every
dependency upgraded, vendor/ removed.
- staticcheck, govulncheck and goimports pinned as go tools; add a
Makefile, CI workflow, goreleaser v2 config and Alpine Dockerfile.
Features
- Background print queue with job status (GET /api/v1/jobs/:id), send
retries with backoff, and graceful shutdown.
- New {"elements": [...]} job format on POST /api/v1/print. Breaking:
replaces {"data": [...]}, and the response is now JSON 202.
- In-house ESC/POS library replacing justinmichaelvieira/escpos: sizes
1-8, Font B, CODE39/CODE128, QR, banded raster images, DLE EOT status.
- UTF-8 text transcoded to CP437 (configurable) with word-aware wrapping.
- Images from URL or base64, scaled and dithered; URL fetches refuse
internal addresses (SSRF guard).
- Fiber v3 HTTP server, TypeID (UUIDv7) job and request IDs, /healthz
with live printer status, `secret` and `token` subcommands.
Fixes
- Jobs are validated before anything is sent; a failed printer dial no
longer panics.
- Request logs never contain tokens; Sentry no longer receives the
Authorization header or print contents.
- Rate limiting is per client behind nginx (X-Real-IP).
- install.sh writes the [printer] section, runs the service as a
dedicated user and uses a current nginx TLS config.
config.toml is no longer tracked; start from configs/config.example.toml.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
bb73348433
commit
6502d9551d
807 files changed
+6659
-500291
No files matched your search
+9
-51
@@ -1,56 +1,14 @@
|
|||||||
# Binaries for programs and plugins
|
# Only the Go sources are needed to build the image.
|
||||||
|
.git
|
||||||
|
.github
|
||||||
|
.idea
|
||||||
|
.vscode
|
||||||
|
bin
|
||||||
|
dist
|
||||||
*.exe
|
*.exe
|
||||||
*.dll
|
|
||||||
*.so
|
|
||||||
*.dylib
|
|
||||||
.idea/*
|
|
||||||
|
|
||||||
# Test binary, build with `go test -c`
|
|
||||||
*.test
|
*.test
|
||||||
|
|
||||||
# Output of the go coverage tool, specifically when used with LiteIDE
|
|
||||||
*.out
|
*.out
|
||||||
|
config.toml
|
||||||
# Project-local glide cache, RE: https://github.com/Masterminds/glide/issues/736
|
|
||||||
.glide/
|
|
||||||
|
|
||||||
# dep related files and folders
|
|
||||||
/vendor*
|
|
||||||
|
|
||||||
# ignore logfiles (/* so the .gitkeep override works)
|
|
||||||
/logs/*
|
|
||||||
|
|
||||||
# ignore configuration file
|
|
||||||
/config.yml
|
|
||||||
|
|
||||||
# Ignore Vagrant stuff
|
|
||||||
/.vagrant
|
|
||||||
|
|
||||||
# Builds by gox
|
|
||||||
/build
|
|
||||||
|
|
||||||
# Go Coverage tool
|
|
||||||
/coverage.out
|
|
||||||
|
|
||||||
# The built executable
|
|
||||||
observatron
|
|
||||||
|
|
||||||
# IDE/Editor files (VS Code)
|
|
||||||
/.vscode
|
|
||||||
|
|
||||||
# test files
|
|
||||||
test_*/
|
|
||||||
|
|
||||||
# Keep all gitkeep files (This needs to stay at the bottom)
|
|
||||||
!.gitkeep
|
|
||||||
debug
|
|
||||||
.DS_Store
|
|
||||||
*.pprof
|
|
||||||
*.pdf
|
|
||||||
|
|
||||||
Dockerfile
|
Dockerfile
|
||||||
CHANGELOG.md
|
|
||||||
Makefile
|
|
||||||
README.md
|
README.md
|
||||||
|
install.sh
|
||||||
/dist
|
|
||||||
+14
-6
@@ -1,14 +1,22 @@
|
|||||||
# EditorConfig is awesome: https://EditorConfig.org
|
# EditorConfig: https://EditorConfig.org
|
||||||
|
|
||||||
# top-most EditorConfig file
|
|
||||||
root = true
|
root = true
|
||||||
|
|
||||||
# Unix-style newlines with a newline ending every file
|
|
||||||
[*]
|
[*]
|
||||||
|
charset = utf-8
|
||||||
end_of_line = lf
|
end_of_line = lf
|
||||||
insert_final_newline = true
|
insert_final_newline = true
|
||||||
|
trim_trailing_whitespace = true
|
||||||
|
|
||||||
# Tab indentation
|
|
||||||
[*.go]
|
[*.go]
|
||||||
indent_style = tab
|
indent_style = tab
|
||||||
indent_size = 4
|
indent_size = 4
|
||||||
|
|
||||||
|
[Makefile]
|
||||||
|
indent_style = tab
|
||||||
|
|
||||||
|
[*.{yml,yaml,toml,md,sh}]
|
||||||
|
indent_style = space
|
||||||
|
indent_size = 2
|
||||||
|
|
||||||
|
[*.md]
|
||||||
|
trim_trailing_whitespace = false
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
# Keep LF line endings everywhere: gofmt rejects CRLF, and install.sh must
|
||||||
|
# run on Linux even when checked out on Windows.
|
||||||
|
* text=auto eol=lf
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
name: CI
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
pull_request:
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
check:
|
||||||
|
name: Lint, test and scan
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Set up Go
|
||||||
|
uses: actions/setup-go@v5
|
||||||
|
with:
|
||||||
|
# Latest patch of the current release, so standard-library security
|
||||||
|
# fixes are picked up without editing this file.
|
||||||
|
go-version: "1.27.x"
|
||||||
|
check-latest: true
|
||||||
|
|
||||||
|
- name: gofmt
|
||||||
|
run: |
|
||||||
|
unformatted="$(gofmt -l .)"
|
||||||
|
if [ -n "$unformatted" ]; then
|
||||||
|
echo "These files need gofmt:"; echo "$unformatted"; exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
- name: go vet
|
||||||
|
run: go vet ./...
|
||||||
|
|
||||||
|
- name: staticcheck
|
||||||
|
run: go tool staticcheck ./...
|
||||||
|
|
||||||
|
- name: Test (race detector)
|
||||||
|
run: go test -race ./...
|
||||||
|
|
||||||
|
- name: govulncheck
|
||||||
|
run: go tool govulncheck ./...
|
||||||
@@ -2,36 +2,33 @@ name: Create Release & Upload Assets
|
|||||||
|
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
# Sequence of patterns matched against refs/tags
|
|
||||||
tags:
|
tags:
|
||||||
- 'v*' # Push events to matching v*, i.e. v1.0, v20.15.10
|
- "v*" # e.g. v1.0, v20.15.10
|
||||||
|
|
||||||
env:
|
|
||||||
VERSION_TAG: '${{ github.ref_name }}'
|
|
||||||
CURL_TOKEN: '${{ secrets.TOKEN_GITEA }}'
|
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
goreleaser:
|
goreleaser:
|
||||||
name: Upload Assets To Gitea w/ goreleaser
|
name: Upload Assets To Gitea w/ goreleaser
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
-
|
- name: Checkout
|
||||||
name: Checkout
|
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
with:
|
with:
|
||||||
fetch-depth: 0
|
fetch-depth: 0
|
||||||
-
|
|
||||||
name: Set up Go
|
- name: Set up Go
|
||||||
uses: actions/setup-go@v5
|
uses: actions/setup-go@v5
|
||||||
with:
|
with:
|
||||||
go-version: 1.22
|
go-version: "1.27.x"
|
||||||
-
|
check-latest: true
|
||||||
name: Run GoReleaser
|
|
||||||
|
- name: Run GoReleaser
|
||||||
uses: goreleaser/goreleaser-action@v6
|
uses: goreleaser/goreleaser-action@v6
|
||||||
with:
|
with:
|
||||||
distribution: goreleaser
|
distribution: goreleaser
|
||||||
version: v1.26.2
|
version: "~> v2"
|
||||||
args: release --clean
|
args: release --clean
|
||||||
env:
|
env:
|
||||||
GITEA_TOKEN: ${{ secrets.TOKEN_GITEA }}
|
GITEA_TOKEN: ${{ secrets.TOKEN_GITEA }}
|
||||||
GORELEASER_FORCE_TOKEN: gitea
|
GORELEASER_FORCE_TOKEN: gitea
|
||||||
|
# Optional default Sentry DSN baked into release binaries.
|
||||||
|
SENTRY_DSN: ${{ secrets.SENTRY_DSN }}
|
||||||
+13
-125
@@ -1,132 +1,20 @@
|
|||||||
# ---> Go
|
# Build output
|
||||||
# If you prefer the allow list template instead of the deny list, see community template:
|
/bin/
|
||||||
# https://github.com/github/gitignore/blob/main/community/Golang/Go.AllowList.gitignore
|
/dist/
|
||||||
#
|
|
||||||
# Binaries for programs and plugins
|
|
||||||
*.exe
|
*.exe
|
||||||
*.exe~
|
|
||||||
*.dll
|
|
||||||
*.so
|
|
||||||
*.dylib
|
|
||||||
|
|
||||||
# Test binary, built with `go test -c`
|
|
||||||
*.test
|
*.test
|
||||||
|
|
||||||
# Output of the go coverage tool, specifically when used with LiteIDE
|
|
||||||
*.out
|
*.out
|
||||||
|
coverage.*
|
||||||
|
|
||||||
# Dependency directories (remove the comment below to include it)
|
# Local configuration: holds the API secret. Start from configs/config.example.toml.
|
||||||
# vendor/
|
/config.toml
|
||||||
|
|
||||||
# Go workspace file
|
# Go workspace
|
||||||
go.work
|
go.work
|
||||||
|
go.work.sum
|
||||||
|
|
||||||
# ---> C
|
# Editors and OS
|
||||||
# Prerequisites
|
.idea/
|
||||||
*.d
|
.vscode/
|
||||||
|
*.swp
|
||||||
# Object files
|
.DS_Store
|
||||||
*.o
|
|
||||||
*.ko
|
|
||||||
*.obj
|
|
||||||
*.elf
|
|
||||||
|
|
||||||
# Linker output
|
|
||||||
*.ilk
|
|
||||||
*.map
|
|
||||||
*.exp
|
|
||||||
|
|
||||||
# Precompiled Headers
|
|
||||||
*.gch
|
|
||||||
*.pch
|
|
||||||
|
|
||||||
# Libraries
|
|
||||||
*.lib
|
|
||||||
*.a
|
|
||||||
*.la
|
|
||||||
*.lo
|
|
||||||
|
|
||||||
# Shared objects (inc. Windows DLLs)
|
|
||||||
*.dll
|
|
||||||
*.so
|
|
||||||
*.so.*
|
|
||||||
*.dylib
|
|
||||||
|
|
||||||
# Executables
|
|
||||||
*.exe
|
|
||||||
*.out
|
|
||||||
*.app
|
|
||||||
*.i*86
|
|
||||||
*.x86_64
|
|
||||||
*.hex
|
|
||||||
|
|
||||||
# Debug files
|
|
||||||
*.dSYM/
|
|
||||||
*.su
|
|
||||||
*.idb
|
|
||||||
*.pdb
|
|
||||||
|
|
||||||
# Kernel Module Compile Results
|
|
||||||
*.cmd
|
|
||||||
.tmp_versions/
|
|
||||||
modules.order
|
|
||||||
Module.symvers
|
|
||||||
Mkfile.old
|
|
||||||
dkms.conf
|
|
||||||
|
|
||||||
# ---> C++
|
|
||||||
# Prerequisites
|
|
||||||
*.d
|
|
||||||
|
|
||||||
# Compiled Object files
|
|
||||||
*.slo
|
|
||||||
*.lo
|
|
||||||
*.o
|
|
||||||
*.obj
|
|
||||||
|
|
||||||
# Precompiled Headers
|
|
||||||
*.gch
|
|
||||||
*.pch
|
|
||||||
|
|
||||||
# Compiled Dynamic libraries
|
|
||||||
*.so
|
|
||||||
*.dylib
|
|
||||||
*.dll
|
|
||||||
|
|
||||||
# Fortran module files
|
|
||||||
*.smod
|
|
||||||
|
|
||||||
# Compiled Static libraries
|
|
||||||
*.lai
|
|
||||||
*.la
|
|
||||||
*.a
|
|
||||||
*.lib
|
|
||||||
|
|
||||||
# Executables
|
|
||||||
*.exe
|
|
||||||
*.out
|
|
||||||
*.app
|
|
||||||
|
|
||||||
# ---> Laravel
|
|
||||||
npm-debug.log
|
|
||||||
yarn-error.log
|
|
||||||
|
|
||||||
# Laravel 4 specific
|
|
||||||
bootstrap/compiled.php
|
|
||||||
app/storage/
|
|
||||||
|
|
||||||
# Laravel 5 & Lumen specific
|
|
||||||
public/storage
|
|
||||||
public/hot
|
|
||||||
|
|
||||||
# Laravel 5 & Lumen specific with changed public path
|
|
||||||
public_html/storage
|
|
||||||
public_html/hot
|
|
||||||
|
|
||||||
storage/*.key
|
|
||||||
.env
|
|
||||||
Homestead.yaml
|
|
||||||
Homestead.json
|
|
||||||
/.vagrant
|
|
||||||
.phpunit.result.cache
|
|
||||||
|
|
||||||
+22
-33
@@ -1,22 +1,24 @@
|
|||||||
|
version: 2
|
||||||
|
|
||||||
project_name: uberbringer
|
project_name: uberbringer
|
||||||
force_token: gitea
|
force_token: gitea
|
||||||
gitea_urls:
|
gitea_urls:
|
||||||
api: https://git.anomalous.dev/api/v1
|
api: https://git.anomalous.dev/api/v1
|
||||||
download: https://git.anomalous.dev/
|
download: https://git.anomalous.dev/
|
||||||
skip_tls_verify: false
|
skip_tls_verify: false
|
||||||
|
|
||||||
before:
|
before:
|
||||||
hooks:
|
hooks:
|
||||||
# You may remove this if you don't use go modules.
|
|
||||||
#- go mod download
|
|
||||||
- go mod tidy
|
- go mod tidy
|
||||||
#- go mod vendor
|
|
||||||
# you may remove this if you don't need go generate
|
|
||||||
- go generate
|
|
||||||
builds:
|
builds:
|
||||||
-
|
- id: uberbringer
|
||||||
id: uberbringer
|
main: ./cmd/uberbringer
|
||||||
|
binary: uberbringer
|
||||||
env:
|
env:
|
||||||
- CGO_ENABLED=0
|
- CGO_ENABLED=0
|
||||||
|
flags:
|
||||||
|
- -trimpath
|
||||||
goos:
|
goos:
|
||||||
- linux
|
- linux
|
||||||
goarch:
|
goarch:
|
||||||
@@ -24,39 +26,26 @@ builds:
|
|||||||
- arm
|
- arm
|
||||||
- arm64
|
- arm64
|
||||||
goarm:
|
goarm:
|
||||||
- 6
|
- "6"
|
||||||
- 7
|
- "7"
|
||||||
main: ./uberbringer.go
|
|
||||||
binary: uberbringer
|
|
||||||
ldflags:
|
ldflags:
|
||||||
- -w -X uberbringer/config.Version={{.Version}} -X uberbringer/config.Build={{.ShortCommit}} -X uberbringer/config.SentryDSN=https://70209de06de24662a0f43b47a99de86b@sentry.alphacentri.com/2
|
# SENTRY_DSN comes from a CI secret; when unset, binaries report
|
||||||
|
# nothing unless sentry.dsn or the SENTRY_DSN env var is configured.
|
||||||
|
- -s -w -X main.version={{ .Version }} -X main.commit={{ .ShortCommit }} -X main.sentryDSN={{ index .Env "SENTRY_DSN" }}
|
||||||
|
|
||||||
archives:
|
archives:
|
||||||
-
|
- formats: [tar]
|
||||||
# Can be used to change the archive formats for specific GOOSs.
|
name_template: "{{ .ProjectName }}_{{ .Os }}_{{ .Arch }}{{ if .Arm }}v{{ .Arm }}{{ end }}"
|
||||||
# Most common use case is to archive as zip on Windows.
|
|
||||||
# Default is empty.
|
|
||||||
name_template: "{{ .ProjectName }}_{{ .Os }}_{{ .Arch }}{{ if .Arm }}v{{ .Arm }}{{ end }}{{ if .Mips }}_{{ .Mips }}{{ end }}"
|
|
||||||
format: 'tar'
|
|
||||||
format_overrides:
|
|
||||||
- goos: windows
|
|
||||||
format: zip
|
|
||||||
source:
|
source:
|
||||||
enabled: true
|
enabled: true
|
||||||
name_template: '{{ .ProjectName }}_{{ .Version }}'
|
name_template: "{{ .ProjectName }}_{{ .Version }}"
|
||||||
|
|
||||||
checksum:
|
checksum:
|
||||||
name_template: 'checksums.txt'
|
name_template: checksums.txt
|
||||||
|
|
||||||
release:
|
release:
|
||||||
# Repo in which the release will be created.
|
|
||||||
# Default is extracted from the origin remote URL or empty if its private hosted.
|
|
||||||
# Note: it can only be one: either github, gitlab or gitea
|
|
||||||
gitea:
|
gitea:
|
||||||
owner: 57_Wolve
|
owner: 57_Wolve
|
||||||
name: uberbringer
|
name: uberbringer
|
||||||
draft: false
|
draft: false
|
||||||
scoop:
|
|
||||||
url_template: "https://git.anomalous.dev/57_Wolve/uberbringer/releases/download/{{ .Tag }}/{{ .ArtifactName }}"
|
|
||||||
# Git author used to commit to the repository.
|
|
||||||
# Defaults are shown.
|
|
||||||
commit_author:
|
|
||||||
name: 57_Wolve
|
|
||||||
email: william.gill@anomalous.dev
|
|
||||||
Generated
-8
@@ -1,8 +0,0 @@
|
|||||||
# Default ignored files
|
|
||||||
/shelf/
|
|
||||||
/workspace.xml
|
|
||||||
# Editor-based HTTP Client requests
|
|
||||||
/httpRequests/
|
|
||||||
# Datasource local storage ignored files
|
|
||||||
/dataSources/
|
|
||||||
/dataSources.local.xml
|
|
||||||
Generated
-7
@@ -1,7 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<project version="4">
|
|
||||||
<component name="DiscordProjectSettings">
|
|
||||||
<option name="show" value="PROJECT_FILES" />
|
|
||||||
<option name="description" value="" />
|
|
||||||
</component>
|
|
||||||
</project>
|
|
||||||
Generated
-8
@@ -1,8 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<project version="4">
|
|
||||||
<component name="ProjectModuleManager">
|
|
||||||
<modules>
|
|
||||||
<module fileurl="file://$PROJECT_DIR$/.idea/uberbringer.iml" filepath="$PROJECT_DIR$/.idea/uberbringer.iml" />
|
|
||||||
</modules>
|
|
||||||
</component>
|
|
||||||
</project>
|
|
||||||
Generated
-9
@@ -1,9 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<module type="WEB_MODULE" version="4">
|
|
||||||
<component name="Go" enabled="true" />
|
|
||||||
<component name="NewModuleRootManager">
|
|
||||||
<content url="file://$MODULE_DIR$" />
|
|
||||||
<orderEntry type="inheritedJdk" />
|
|
||||||
<orderEntry type="sourceFolder" forTests="false" />
|
|
||||||
</component>
|
|
||||||
</module>
|
|
||||||
Generated
-6
@@ -1,6 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<project version="4">
|
|
||||||
<component name="VcsDirectoryMappings">
|
|
||||||
<mapping directory="" vcs="Git" />
|
|
||||||
</component>
|
|
||||||
</project>
|
|
||||||
+25
@@ -0,0 +1,25 @@
|
|||||||
|
# syntax=docker/dockerfile:1
|
||||||
|
|
||||||
|
FROM golang:1.27-alpine AS build
|
||||||
|
WORKDIR /src
|
||||||
|
COPY go.mod go.sum ./
|
||||||
|
RUN go mod download
|
||||||
|
COPY . .
|
||||||
|
ARG VERSION=dev
|
||||||
|
ARG COMMIT=none
|
||||||
|
RUN CGO_ENABLED=0 go build -trimpath \
|
||||||
|
-ldflags "-s -w -X main.version=${VERSION} -X main.commit=${COMMIT}" \
|
||||||
|
-o /out/uberbringer ./cmd/uberbringer
|
||||||
|
|
||||||
|
FROM alpine:3.24
|
||||||
|
# ca-certificates for fetching https images, tzdata for local log times.
|
||||||
|
RUN apk add --no-cache ca-certificates tzdata \
|
||||||
|
&& addgroup -S uberbringer \
|
||||||
|
&& adduser -S -D -H -G uberbringer -h /etc/uberbringer uberbringer
|
||||||
|
COPY --from=build /out/uberbringer /usr/local/bin/uberbringer
|
||||||
|
USER uberbringer
|
||||||
|
WORKDIR /etc/uberbringer
|
||||||
|
# Mount config.toml at /etc/uberbringer/config.toml with bind_ip = "0.0.0.0".
|
||||||
|
EXPOSE 8080
|
||||||
|
ENTRYPOINT ["/usr/local/bin/uberbringer"]
|
||||||
|
CMD ["--config", "/etc/uberbringer/config.toml"]
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
.PHONY: build test lint fmt vet tidy vuln check run
|
||||||
|
|
||||||
|
VERSION ?= $(shell git describe --tags --always --dirty 2>/dev/null || echo dev)
|
||||||
|
COMMIT ?= $(shell git rev-parse --short HEAD 2>/dev/null || echo none)
|
||||||
|
LDFLAGS := -s -w -X main.version=$(VERSION) -X main.commit=$(COMMIT)
|
||||||
|
|
||||||
|
build:
|
||||||
|
go build -trimpath -ldflags "$(LDFLAGS)" -o bin/ ./cmd/...
|
||||||
|
|
||||||
|
test:
|
||||||
|
go test -race ./...
|
||||||
|
|
||||||
|
lint:
|
||||||
|
go tool staticcheck ./...
|
||||||
|
|
||||||
|
# gofmt and goimports take paths, not ./... package patterns.
|
||||||
|
fmt:
|
||||||
|
gofmt -w .
|
||||||
|
go tool goimports -w .
|
||||||
|
|
||||||
|
vet:
|
||||||
|
go vet ./...
|
||||||
|
|
||||||
|
tidy:
|
||||||
|
go mod tidy
|
||||||
|
|
||||||
|
vuln:
|
||||||
|
go tool govulncheck ./...
|
||||||
|
|
||||||
|
# Everything CI runs.
|
||||||
|
check: vet lint test vuln
|
||||||
|
@test -z "$$(gofmt -l .)" || (echo "gofmt needed:"; gofmt -l .; exit 1)
|
||||||
|
|
||||||
|
run:
|
||||||
|
go run ./cmd/uberbringer --config config.toml
|
||||||
@@ -1,52 +1,324 @@
|
|||||||
# Überbringer
|
# Überbringer
|
||||||
|
|
||||||
Bringer of information
|
*Bringer of information.* A small daemon that takes print jobs as JSON over a
|
||||||
|
REST API and prints them on an EPSON ESC/POS network receipt printer.
|
||||||
|
|
||||||
EPOS Network Printer via REST API
|
- **Queue with job status**: jobs return immediately with an ID and print in
|
||||||
|
order on a background worker, with retries when the printer is offline.
|
||||||
|
- **Plain-text input**: send UTF-8 text, including accents, `£ ° ±` and
|
||||||
|
box-drawing `┌─┐│└┘░▒▓`. It is transcoded to the printer's code page
|
||||||
|
(CP437 by default).
|
||||||
|
- **Word wrap**: text wraps at word boundaries for the paper width and
|
||||||
|
character size, so words are never cut in half.
|
||||||
|
- **Rich elements**: bold, underline, inverse, sizes 1–8, two fonts,
|
||||||
|
alignment, QR codes, EAN/UPC/CODE39/CODE128 barcodes, images, raw ESC/POS.
|
||||||
|
- **Images that print well**: PNG, JPEG, GIF or WebP from a URL or base64,
|
||||||
|
scaled to the paper and dithered. Image URLs can't reach internal network
|
||||||
|
addresses unless you allow it.
|
||||||
|
- **Health endpoint** with live printer status: paper low or out, cover open,
|
||||||
|
errors.
|
||||||
|
|
||||||
Just a fun little project to take a REST API input and generate an output to a network printer.
|
## Contents
|
||||||
|
|
||||||
|
- [Quick start](#quick-start)
|
||||||
|
- [API](#api)
|
||||||
|
- [Elements](#elements)
|
||||||
|
- [Migrating from the old format](#migrating-from-the-old-format)
|
||||||
|
- [Configuration](#configuration)
|
||||||
|
- [Command line](#command-line)
|
||||||
|
- [Development](#development)
|
||||||
|
|
||||||
|
## Quick start
|
||||||
|
|
||||||
# TO DO
|
### Debian/Ubuntu server with nginx and TLS
|
||||||
- Print Queue for incoming jobs (create background loop that checks queue)
|
|
||||||
- Re-work API Data Input Format to slim it down for basic commands that don't need size/text input.
|
|
||||||
|
|
||||||
## Example Usage:
|
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sudo ./install.sh printer.example.com you@example.com 192.168.1.245
|
||||||
```
|
```
|
||||||
curl --request POST \
|
|
||||||
--url http://127.0.0.1:8080/api/v1/print \
|
The script installs the latest release as a systemd service running as a
|
||||||
--header 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoidWJlcmJyaW5nZXIifQ.TWB3oK8fuoad7oP6FHTP7HhAQB7iRhZRtL1N71irVNc' \
|
dedicated `uberbringer` user. It also sets up nginx with a Let's Encrypt
|
||||||
--header 'Content-Type: application/json' \
|
certificate, writes `/etc/uberbringer/config.toml` with a fresh secret, and
|
||||||
--header 'User-Agent: Insomnia/2023.5.5' \
|
prints an API token.
|
||||||
--data '{
|
|
||||||
"data": [
|
### Docker
|
||||||
{
|
|
||||||
"type": 6,
|
```sh
|
||||||
"size": 1,
|
docker build -t uberbringer .
|
||||||
"text": "B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2"
|
docker run -d -p 8080:8080 -v "$PWD/config.toml:/etc/uberbringer/config.toml:ro" uberbringer
|
||||||
},
|
```
|
||||||
{
|
|
||||||
"type": 6,
|
Inside a container, set `bind_ip = "0.0.0.0"` in the `[webserver]` section.
|
||||||
"size": 1,
|
|
||||||
"text": "2020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020DAC4C4C4C4C4C4C4C4C4C4C4C4C4C4C4C4C4C4BF20202020202020202020202020202020202020202020B3202121212041434854554E47202121212020B320202020202020202020202020202020202020202020C0C4C4C4C4C4C4C4C4C4C4C4C4C4C4C4C4C4C4D92020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020"
|
### From source
|
||||||
},
|
|
||||||
{
|
```sh
|
||||||
"type": 6,
|
cp configs/config.example.toml config.toml
|
||||||
"size": 1,
|
go run ./cmd/uberbringer secret # paste into api.secret
|
||||||
"text": "B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2B2"
|
$EDITOR config.toml # set printer.address
|
||||||
},
|
go run ./cmd/uberbringer token # prints a bearer token
|
||||||
{
|
make run
|
||||||
"type": 6,
|
```
|
||||||
"size": 1,
|
|
||||||
"text": "202020202020202020202020202020205F0A2020202020202020202020202020207C455D0A202020202020202020202020202E2D7C3D3D3D3D3D2D2E0A202020202020202020202020207C207C206D61696C207C0A202020202020202020205F5F5F7C5F5F5F5F5F5F5F5F7C0A20202020202020202020202020202020207C7C0A20202020202020202020202020202020207C7C0A20202020202020202020202020202020207C7C2020207777770A202020202020202020202C3B2C202020207C7C202020295F282C3B3B3B2C0A202020202020202020203C5F3E20205C207C7C2020205C7C2F205C5F2F0A202020202020202020205C7C2F20205C5C7C7C20205C5C7C2020207C2F2F0A5F5F5F5F5F5F5F5F5F5F5C7C2F2F5F5C5C7C2F2F2F5F5C562F5F5C7C2F2F5F5F5F5F5F5F5F5F5F5F5F5F"
|
## API
|
||||||
},
|
|
||||||
{
|
All `/api/v1` routes need an `Authorization: Bearer <token>` header. Issue
|
||||||
"type": 5,
|
tokens with `uberbringer token`. Tokens created by the old install script keep
|
||||||
"size": 3,
|
working as long as the secret is unchanged. Tokens in query strings are not
|
||||||
"text": ""
|
accepted, because they leak into proxy logs.
|
||||||
}
|
|
||||||
|
| Method | Path | Purpose |
|
||||||
|
|--------|--------------------|------------------------------------------|
|
||||||
|
| POST | `/api/v1/print` | Queue a print job |
|
||||||
|
| GET | `/api/v1/jobs/:id` | Job status |
|
||||||
|
| GET | `/healthz` | Printer and queue health (no auth) |
|
||||||
|
| GET | `/` | Version information (no auth) |
|
||||||
|
|
||||||
|
### Print a receipt
|
||||||
|
|
||||||
|
```sh
|
||||||
|
curl -X POST https://printer.example.com/api/v1/print \
|
||||||
|
-H "Authorization: Bearer $TOKEN" \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-d '{
|
||||||
|
"elements": [
|
||||||
|
{"type": "text", "text": "▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓"},
|
||||||
|
{"type": "text", "text": "┌─────────────────────┐\n│ !!! ACHTUNG !!! │\n└─────────────────────┘", "align": "center"},
|
||||||
|
{"type": "text", "text": "Überbringer", "size": 2, "bold": true, "align": "center"},
|
||||||
|
{"type": "feed"},
|
||||||
|
{"type": "text", "text": "Long paragraphs wrap at word boundaries for the paper width, so a word is never split across two lines."},
|
||||||
|
{"type": "text", "text": "Total: ", "newline": false},
|
||||||
|
{"type": "text", "text": "£12.50", "bold": true},
|
||||||
|
{"type": "qr", "data": "https://example.com", "align": "center"},
|
||||||
|
{"type": "feed", "lines": 3}
|
||||||
]
|
]
|
||||||
}'
|
}'
|
||||||
```
|
```
|
||||||
|
|
||||||
|
The response is `202 Accepted` with a `Location` header:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{"id": "job_01kbx4n6m3ex8tq0wq3r5vrzq1", "status": "queued", "created_at": "2026-11-29T21:04:05Z"}
|
||||||
|
```
|
||||||
|
|
||||||
|
Job IDs are [TypeIDs](https://github.com/jetify-com/typeid): UUIDv7 values
|
||||||
|
with a `job_` prefix, so they sort by creation time.
|
||||||
|
|
||||||
|
### Job status
|
||||||
|
|
||||||
|
```sh
|
||||||
|
curl -H "Authorization: Bearer $TOKEN" https://printer.example.com/api/v1/jobs/job_01kbx4n6m3ex8tq0wq3r5vrzq1
|
||||||
|
```
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"id": "job_01kbx4n6m3ex8tq0wq3r5vrzq1",
|
||||||
|
"status": "done",
|
||||||
|
"attempts": 1,
|
||||||
|
"created_at": "2026-11-29T21:04:05Z",
|
||||||
|
"started_at": "2026-11-29T21:04:05Z",
|
||||||
|
"finished_at": "2026-11-29T21:04:06Z"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`status` is `queued`, `printing`, `done` or `failed`. A failed job includes an
|
||||||
|
`error` field. The last `queue.history` finished jobs are kept.
|
||||||
|
|
||||||
|
### Health
|
||||||
|
|
||||||
|
`GET /healthz` returns `200` when the printer is reachable and ready, and
|
||||||
|
`503` when it is unreachable or not ready (paper out, cover open, error).
|
||||||
|
|
||||||
|
```json
|
||||||
|
{"status": "ok", "printer": {"reachable": true, "status": "ready", "online": true, "cover_open": false, "paper": "near_end"}, "queue": {"pending": 0}}
|
||||||
|
```
|
||||||
|
|
||||||
|
A printer that accepts connections but does not answer status requests is
|
||||||
|
reported as `"status": "unknown"` with HTTP `200`.
|
||||||
|
|
||||||
|
### Errors
|
||||||
|
|
||||||
|
Errors are JSON: `{"error": "message", "details": ["..."]}`.
|
||||||
|
|
||||||
|
| Status | Meaning |
|
||||||
|
|--------|---------|
|
||||||
|
| 400 | Malformed JSON, an unknown field, or invalid elements. `details` lists every problem, e.g. `elements[2] (text): size, width and height must be 1-8` |
|
||||||
|
| 401 | Missing, invalid or expired token |
|
||||||
|
| 404 | Unknown route or job |
|
||||||
|
| 413 | Body larger than `webserver.body_limit` |
|
||||||
|
| 429 | Rate limit exceeded |
|
||||||
|
| 503 | Queue full (with `Retry-After`) or the server is shutting down |
|
||||||
|
|
||||||
|
Validation happens before a job is queued. Images are fetched by the worker,
|
||||||
|
so a blocked or broken image URL shows up as a `failed` job. Nothing is sent
|
||||||
|
to the printer unless the whole receipt rendered.
|
||||||
|
|
||||||
|
## Elements
|
||||||
|
|
||||||
|
A job is `{"elements": [...], "copies": 1}`. `copies` is 1–5, and each copy is
|
||||||
|
cut separately. A partial cut is added after the last element unless that
|
||||||
|
element is already a `cut`.
|
||||||
|
|
||||||
|
### `text`
|
||||||
|
|
||||||
|
| Field | Default | Values |
|
||||||
|
|-------------|---------|--------|
|
||||||
|
| `text` | `""` | UTF-8 text. `\n` starts a new line |
|
||||||
|
| `size` | `1` | 1–8, sets width and height |
|
||||||
|
| `width`, `height` | `size` | 1–8 each, for stretched text |
|
||||||
|
| `bold` | `false` | |
|
||||||
|
| `underline` | `0` | 0, 1 (thin) or 2 (thick) |
|
||||||
|
| `invert` | `false` | white on black |
|
||||||
|
| `font` | `a` | `a` (48 columns on 80 mm) or `b` (64 columns, smaller) |
|
||||||
|
| `align` | `left` | `left`, `center`, `right` |
|
||||||
|
| `newline` | `true` | `false` keeps the next element on the same line |
|
||||||
|
| `wrap` | `true` | `false` sends the text as-is and lets the printer wrap |
|
||||||
|
|
||||||
|
**Encoding.** Text is transcoded from UTF-8 to `printer.codepage`, CP437 by
|
||||||
|
default. Characters the code page lacks, such as emoji, print as `?`. Control
|
||||||
|
characters are removed so text can never be read as printer commands.
|
||||||
|
|
||||||
|
**Word wrap.** The line width comes from the printer model and the character
|
||||||
|
size: 48 characters at size 1, 24 at size 2, and so on. Lines break at spaces,
|
||||||
|
and only a word longer than a whole line (a long URL, say) is split. The
|
||||||
|
renderer tracks the position across `"newline": false` elements, so mixed
|
||||||
|
sizes on one line still wrap correctly.
|
||||||
|
|
||||||
|
### `feed`
|
||||||
|
|
||||||
|
| Field | Default | Values |
|
||||||
|
|---------|---------|--------|
|
||||||
|
| `lines` | `1` | 1–255 |
|
||||||
|
|
||||||
|
### `qr`
|
||||||
|
|
||||||
|
| Field | Default | Values |
|
||||||
|
|--------------|---------|--------|
|
||||||
|
| `data` | | Required. Encoded as UTF-8, up to 7089 bytes |
|
||||||
|
| `size` | `6` | Module size in dots, 1–16 |
|
||||||
|
| `correction` | `M` | `L`, `M`, `Q`, `H` |
|
||||||
|
| `align` | `left` | |
|
||||||
|
|
||||||
|
### `barcode`
|
||||||
|
|
||||||
|
| Field | Default | Values |
|
||||||
|
|-------------|---------|--------|
|
||||||
|
| `symbology` | | Required. `ean13`, `ean8`, `upca`, `upce`, `code39`, `code128` |
|
||||||
|
| `data` | | Required. Digits for EAN/UPC, where a supplied check digit is verified. `A–Z 0–9 -.$/+%` and space for CODE39. Printable ASCII for CODE128 |
|
||||||
|
| `height` | `80` | Bar height in dots, 1–255 |
|
||||||
|
| `width` | `3` | Module width, 2–6 |
|
||||||
|
| `hri` | `below` | Human-readable text: `none`, `above`, `below`, `both` |
|
||||||
|
| `align` | `left` | |
|
||||||
|
|
||||||
|
### `image`
|
||||||
|
|
||||||
|
| Field | Default | Values |
|
||||||
|
|----------|---------|--------|
|
||||||
|
| `url` | | `http`/`https` URL, or use `base64` |
|
||||||
|
| `base64` | | Image data, or a `data:image/png;base64,...` URI |
|
||||||
|
| `width` | natural | Target width in dots, up to the paper width (576 on 80 mm) |
|
||||||
|
| `align` | `left` | |
|
||||||
|
|
||||||
|
PNG, JPEG, GIF and WebP are supported. Images wider than the paper are scaled
|
||||||
|
down to fit, and every image is dithered to black and white. URL fetches have
|
||||||
|
a timeout, a size cap and a pixel cap. URLs that resolve to loopback, private
|
||||||
|
or link-local addresses (including cloud metadata endpoints) are refused unless
|
||||||
|
`images.allow_private_networks` is true or the host is in
|
||||||
|
`images.allowed_hosts`.
|
||||||
|
|
||||||
|
### `raw`
|
||||||
|
|
||||||
|
| Field | Values |
|
||||||
|
|-------|--------|
|
||||||
|
| `hex` | ESC/POS bytes as hex, spaces allowed, e.g. `"1B 61 01"` |
|
||||||
|
|
||||||
|
### `cut`
|
||||||
|
|
||||||
|
| Field | Default | Values |
|
||||||
|
|--------|-----------|--------|
|
||||||
|
| `mode` | `partial` | `partial`, `full` |
|
||||||
|
|
||||||
|
## Migrating from the old format
|
||||||
|
|
||||||
|
The endpoint is still `POST /api/v1/print`, but the body changed from
|
||||||
|
`{"data": [...]}` to `{"elements": [...]}`. The response changed from the text
|
||||||
|
`OK - <id>` to the JSON shown above. Old-format bodies get a `400` that points
|
||||||
|
here.
|
||||||
|
|
||||||
|
| Old `type` | Old meaning | New element |
|
||||||
|
|------------|-------------|-------------|
|
||||||
|
| 1 | Text | `{"type": "text", "text": "...", "size": n, "newline": false}` |
|
||||||
|
| 2 | Bold text | `{"type": "text", "text": "...", "bold": true, "newline": false}` |
|
||||||
|
| 3 | QR code | `{"type": "qr", "data": "...", "size": n, "correction": "H"}` |
|
||||||
|
| 4 | Line feed | `{"type": "feed"}` |
|
||||||
|
| 5 | n line feeds | `{"type": "feed", "lines": n}` |
|
||||||
|
| 6 | Raw hex | `{"type": "raw", "hex": "..."}`, or plain UTF-8 `text` for CP437 art |
|
||||||
|
| 7 | Image URL | `{"type": "image", "url": "..."}` |
|
||||||
|
|
||||||
|
Old text items did not end the line, hence `"newline": false`. You can usually
|
||||||
|
drop it now and let each `text` element be a line. Hex-encoded CP437 box
|
||||||
|
drawing can become plain text: `B3 20 21 21 21` is `"│ !!!"`.
|
||||||
|
|
||||||
|
## Configuration
|
||||||
|
|
||||||
|
Copy [configs/config.example.toml](configs/config.example.toml) to
|
||||||
|
`config.toml`. Only `api.secret` (at least 32 bytes) and `printer.address` are
|
||||||
|
required; every other setting has a default, which the example shows. Configs
|
||||||
|
written by the old install script still load. Unknown keys are reported as
|
||||||
|
errors, so a typo can't silently fall back to a default.
|
||||||
|
|
||||||
|
Settings worth knowing:
|
||||||
|
|
||||||
|
- `printer.model`: `tm-t20` (default), `tm-t88`, `generic-80mm` or
|
||||||
|
`generic-58mm`. It sets the paper width and characters per line.
|
||||||
|
`paper_width` and `columns` override it.
|
||||||
|
- `printer.codepage`: `cp437` (default), `cp850`, `cp858` (has €) or
|
||||||
|
`cp1252`.
|
||||||
|
- `webserver.trusted_proxies` / `proxy_header`: the real client IP for
|
||||||
|
per-client rate limits comes from the `X-Real-IP` header set by nginx on
|
||||||
|
`127.0.0.1`.
|
||||||
|
- `sentry.dsn`: error reporting. Falls back to the `SENTRY_DSN` environment
|
||||||
|
variable, then to a DSN built into release binaries (from the `SENTRY_DSN`
|
||||||
|
CI secret). Request bodies are never sent to Sentry.
|
||||||
|
|
||||||
|
## Command line
|
||||||
|
|
||||||
|
```text
|
||||||
|
uberbringer [--config config.toml] run the daemon (default command)
|
||||||
|
uberbringer secret print a new random API secret
|
||||||
|
uberbringer token [--subject s] [--ttl 720h] print a signed bearer token
|
||||||
|
uberbringer version print the version
|
||||||
|
```
|
||||||
|
|
||||||
|
The daemon shuts down gracefully on SIGINT/SIGTERM. A receipt that is already
|
||||||
|
printing is finished, and jobs still waiting are marked failed.
|
||||||
|
|
||||||
|
## Development
|
||||||
|
|
||||||
|
Go 1.26 or newer is required. Use the latest patch release, since govulncheck
|
||||||
|
flags standard-library fixes.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
make check # gofmt, go vet, staticcheck, go test -race, govulncheck
|
||||||
|
make build # bin/uberbringer
|
||||||
|
make fmt # gofmt + goimports
|
||||||
|
```
|
||||||
|
|
||||||
|
The linters are pinned as Go tools in `go.mod`, so `go tool staticcheck`,
|
||||||
|
`go tool govulncheck` and `go tool goimports` need no separate install.
|
||||||
|
|
||||||
|
```text
|
||||||
|
cmd/uberbringer/ main: build info, signals, exit code
|
||||||
|
internal/app/uberbringer/ CLI commands and wiring
|
||||||
|
server/ Fiber HTTP API, auth, health
|
||||||
|
internal/pkg/config/ TOML config: defaults and validation
|
||||||
|
internal/pkg/escpos/ ESC/POS command builder, code pages, barcodes, QR, raster, status
|
||||||
|
internal/pkg/receipt/ Job format, validation, word wrap, rendering
|
||||||
|
internal/pkg/raster/ Image decoding, scaling and dithering
|
||||||
|
internal/pkg/safehttp/ SSRF-guarded image fetching
|
||||||
|
internal/pkg/printer/ TCP printer client (port 9100) and status queries
|
||||||
|
internal/pkg/printqueue/ Job queue, worker and status history
|
||||||
|
configs/ Example configuration
|
||||||
|
```
|
||||||
|
|
||||||
|
Releases are built by GoReleaser when a `v*` tag is pushed.
|
||||||
-79
@@ -1,79 +0,0 @@
|
|||||||
package cmd
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"log"
|
|
||||||
"strconv"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/liamg/tml"
|
|
||||||
"github.com/spf13/cobra"
|
|
||||||
|
|
||||||
"uberbringer/config"
|
|
||||||
"uberbringer/service"
|
|
||||||
)
|
|
||||||
|
|
||||||
var rootCommand = &cobra.Command{
|
|
||||||
Use: "uberbringer",
|
|
||||||
Short: "Runs the Überbringer daemon.",
|
|
||||||
PreRun: func(cmd *cobra.Command, args []string) {
|
|
||||||
config.GetConfig()
|
|
||||||
startSplash()
|
|
||||||
},
|
|
||||||
Run: func(cmd *cobra.Command, args []string) {
|
|
||||||
startServer()
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
var versionCommand = &cobra.Command{
|
|
||||||
Use: "version",
|
|
||||||
Short: "Prints the current executable version and exits.",
|
|
||||||
Run: func(cmd *cobra.Command, _ []string) {
|
|
||||||
fmt.Printf("%s | Version: %s Build: %s | Copyright © %d William Gill\n", config.Project, config.Version, config.Build, time.Now().Year())
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
func Execute() {
|
|
||||||
if err := rootCommand.Execute(); err != nil {
|
|
||||||
log.Fatalf("failed to execute command: %s", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func init() {
|
|
||||||
rootCommand.PersistentFlags().StringVarP(&config.TOML, "config", "c", "config.toml", "Specify daemon config file.")
|
|
||||||
|
|
||||||
rootCommand.AddCommand(versionCommand)
|
|
||||||
}
|
|
||||||
|
|
||||||
func startSplash() {
|
|
||||||
|
|
||||||
//// ***** Start Console Splash ***** ////
|
|
||||||
tml.Printf("-----------------------------------------------------------------------------------------------\n\n")
|
|
||||||
tml.Printf("<bold> <lightblue>" + config.Project + " | Version: " + config.Version + " Build: " + config.Build + " | Copyright © " + strconv.Itoa(time.Now().Year()) + " William Gill</lightblue> <lightgreen> </bold>\n\n")
|
|
||||||
tml.Printf("<bold> <lightblue>Project:</lightblue> " + config.Project + "</bold>\n")
|
|
||||||
tml.Printf("<bold> <lightblue>Description:</lightblue> " + config.Description + "</bold>\n")
|
|
||||||
tml.Printf("<bold> <lightblue>Authors:</lightblue> " + config.Authors + "</bold>\n\n")
|
|
||||||
|
|
||||||
tml.Printf("-----------------------------------------------------------------------------------------------\n")
|
|
||||||
|
|
||||||
tml.Printf("<bold><cyan>[" + config.Project + "]: Initializing...</cyan></bold>\n")
|
|
||||||
//// ***** End Console Splash ***** ////
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
func startServer() {
|
|
||||||
|
|
||||||
//// ***** Start Echo ***** ////
|
|
||||||
tml.Printf("<bold><cyan>[" + config.Project + "]: Initializing Web Server...</cyan></bold>\n")
|
|
||||||
|
|
||||||
serverChannel := make(chan bool)
|
|
||||||
defer close(serverChannel)
|
|
||||||
// Start Web Server
|
|
||||||
go service.StartEcho(serverChannel, config.WebServerBindIP, config.WebServerPort)
|
|
||||||
// Stream Channel
|
|
||||||
serverData := <-serverChannel
|
|
||||||
fmt.Scanln(serverData)
|
|
||||||
|
|
||||||
//// ***** End Echo ***** ////
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
// Command uberbringer runs the Überbringer receipt printer daemon: a REST API
|
||||||
|
// that prints JSON-described receipts on an EPSON ESC/POS network printer.
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"os/signal"
|
||||||
|
"syscall"
|
||||||
|
|
||||||
|
"git.anomalous.dev/57_Wolve/uberbringer/internal/app/uberbringer"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Set at build time with -ldflags "-X main.version=... -X main.commit=...".
|
||||||
|
var (
|
||||||
|
version = "dev"
|
||||||
|
commit = "none"
|
||||||
|
sentryDSN = ""
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
os.Exit(run())
|
||||||
|
}
|
||||||
|
|
||||||
|
func run() int {
|
||||||
|
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||||
|
defer stop()
|
||||||
|
|
||||||
|
build := uberbringer.BuildInfo{Version: version, Commit: commit, SentryDSN: sentryDSN}
|
||||||
|
if err := uberbringer.Execute(ctx, build, os.Args[1:]); err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "uberbringer: %v\n", err)
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
[webserver]
|
|
||||||
bind_ip = "127.0.0.1"
|
|
||||||
port = 8080
|
|
||||||
|
|
||||||
[api]
|
|
||||||
secret = "xTw8qdxTy7Ng4DiptTqmeVy506xWLht3OhFn4kdawmM="
|
|
||||||
|
|
||||||
[printer]
|
|
||||||
address = "192.168.1.245"
|
|
||||||
@@ -1,73 +0,0 @@
|
|||||||
package config
|
|
||||||
|
|
||||||
import (
|
|
||||||
"log"
|
|
||||||
|
|
||||||
"github.com/BurntSushi/toml"
|
|
||||||
"github.com/liamg/tml"
|
|
||||||
)
|
|
||||||
|
|
||||||
var TOML = ""
|
|
||||||
|
|
||||||
type (
|
|
||||||
Config struct {
|
|
||||||
WebServer struct {
|
|
||||||
Bind_IP string
|
|
||||||
Port int
|
|
||||||
}
|
|
||||||
|
|
||||||
API struct {
|
|
||||||
Secret string
|
|
||||||
}
|
|
||||||
|
|
||||||
Printer struct {
|
|
||||||
Address string
|
|
||||||
}
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
func GetConfig() {
|
|
||||||
tomlData := TOML
|
|
||||||
|
|
||||||
var configData Config
|
|
||||||
_, err := toml.DecodeFile(tomlData, &configData)
|
|
||||||
if err != nil {
|
|
||||||
tml.Printf("<bold><red>[" + Project + "]: Failed to open config file " + TOML + "</red></bold>\n")
|
|
||||||
log.Fatal("Exiting...", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
data := &configData
|
|
||||||
|
|
||||||
JWT_Secret = data.API.Secret
|
|
||||||
WebServerBindIP = data.WebServer.Bind_IP
|
|
||||||
WebServerPort = data.WebServer.Port
|
|
||||||
PrinterAddr = data.Printer.Address
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
// Basic Information
|
|
||||||
const (
|
|
||||||
Project = "Überbringer"
|
|
||||||
Description = "EPSON Receipt Printer Server"
|
|
||||||
Authors = "https://git.anomalous.dev/57_Wolve/uberbringer"
|
|
||||||
)
|
|
||||||
|
|
||||||
var (
|
|
||||||
Version string
|
|
||||||
Build string
|
|
||||||
SentryDSN string
|
|
||||||
)
|
|
||||||
|
|
||||||
// Start Config
|
|
||||||
var (
|
|
||||||
WebServerBindIP string
|
|
||||||
WebServerPort int
|
|
||||||
)
|
|
||||||
|
|
||||||
var (
|
|
||||||
JWT_Secret string
|
|
||||||
)
|
|
||||||
|
|
||||||
var (
|
|
||||||
PrinterAddr string
|
|
||||||
)
|
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
# Überbringer configuration.
|
||||||
|
#
|
||||||
|
# Copy to config.toml and fill in api.secret and printer.address; everything
|
||||||
|
# else is optional and shows its default. Durations use Go syntax: "500ms",
|
||||||
|
# "10s", "1m".
|
||||||
|
|
||||||
|
[webserver]
|
||||||
|
bind_ip = "127.0.0.1" # use "0.0.0.0" inside Docker
|
||||||
|
port = 8080
|
||||||
|
|
||||||
|
# Per-client rate limit on /api: rate_limit requests per rate_window.
|
||||||
|
rate_limit = 60
|
||||||
|
rate_window = "1m"
|
||||||
|
|
||||||
|
# Reverse proxies allowed to report the real client IP in proxy_header.
|
||||||
|
# install.sh configures nginx to set X-Real-IP.
|
||||||
|
trusted_proxies = ["127.0.0.1", "::1"]
|
||||||
|
proxy_header = "X-Real-IP"
|
||||||
|
|
||||||
|
body_limit = 4194304 # bytes (4 MiB); raise it for large base64 images
|
||||||
|
read_timeout = "15s"
|
||||||
|
write_timeout = "15s"
|
||||||
|
idle_timeout = "60s"
|
||||||
|
|
||||||
|
[api]
|
||||||
|
# HS256 key for bearer tokens, at least 32 bytes.
|
||||||
|
# Generate one with: uberbringer secret
|
||||||
|
# Then issue tokens: uberbringer token --subject my-script
|
||||||
|
secret = ""
|
||||||
|
|
||||||
|
[printer]
|
||||||
|
address = "" # printer IP or hostname, e.g. "192.168.1.245"
|
||||||
|
port = 9100
|
||||||
|
|
||||||
|
# tm-t20 (TM-T20/II/III), tm-t88 (TM-T88IV-VII), generic-80mm, generic-58mm
|
||||||
|
model = "tm-t20"
|
||||||
|
|
||||||
|
# Character table that text is transcoded to: cp437 (Epson default,
|
||||||
|
# box-drawing and shading), cp850, cp858 (adds €) or cp1252.
|
||||||
|
codepage = "cp437"
|
||||||
|
|
||||||
|
# paper_width = 576 # printable dots; overrides the model
|
||||||
|
# columns = 48 # Font A characters per line for word wrap
|
||||||
|
|
||||||
|
dial_timeout = "5s"
|
||||||
|
write_timeout = "30s"
|
||||||
|
retries = 3 # resend attempts when the printer is unreachable
|
||||||
|
retry_delay = "1s" # doubles after each attempt
|
||||||
|
|
||||||
|
[queue]
|
||||||
|
size = 100 # jobs that may wait; more get 503
|
||||||
|
history = 1000 # finished jobs whose status is kept
|
||||||
|
|
||||||
|
[images]
|
||||||
|
timeout = "10s"
|
||||||
|
max_bytes = 10485760 # 10 MiB download limit
|
||||||
|
max_pixels = 25000000 # decoded size limit (decompression bombs)
|
||||||
|
max_height = 4000 # printed height limit in dots, about 50 cm
|
||||||
|
|
||||||
|
# Image URLs that resolve to loopback, private or link-local addresses are
|
||||||
|
# refused unless allowed here. allowed_hosts, when set, is the only list of
|
||||||
|
# hosts images may come from, and those hosts may be on your LAN.
|
||||||
|
allow_private_networks = false
|
||||||
|
allowed_hosts = []
|
||||||
|
|
||||||
|
[sentry]
|
||||||
|
dsn = "" # falls back to SENTRY_DSN, then the build default
|
||||||
|
environment = "production"
|
||||||
|
debug = false
|
||||||
|
|
||||||
|
[log]
|
||||||
|
level = "info" # debug, info, warn or error
|
||||||
|
format = "text" # text or json
|
||||||
@@ -1,32 +1,48 @@
|
|||||||
module uberbringer
|
module git.anomalous.dev/57_Wolve/uberbringer
|
||||||
|
|
||||||
go 1.23.4
|
go 1.26.0
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/BurntSushi/toml v1.4.0
|
github.com/BurntSushi/toml v1.6.0
|
||||||
github.com/foize/go.fifo v0.0.0-20130327144150-3a04cfeec121
|
github.com/getsentry/sentry-go v0.50.0
|
||||||
github.com/getsentry/sentry-go v0.31.1
|
github.com/gofiber/fiber/v3 v3.7.0
|
||||||
github.com/getsentry/sentry-go/echo v0.31.1
|
github.com/golang-jwt/jwt/v5 v5.3.1
|
||||||
github.com/golang-jwt/jwt/v5 v5.2.1
|
github.com/liamg/tml v0.7.1
|
||||||
github.com/justinmichaelvieira/escpos v0.1.1
|
github.com/spf13/cobra v1.10.2
|
||||||
github.com/labstack/echo-jwt/v4 v4.3.0
|
go.jetify.com/typeid v1.3.0
|
||||||
github.com/labstack/echo/v4 v4.13.3
|
golang.org/x/image v0.48.0
|
||||||
github.com/liamg/tml v0.7.0
|
golang.org/x/sync v0.25.0
|
||||||
github.com/spf13/cobra v1.8.1
|
golang.org/x/text v0.44.0
|
||||||
golang.org/x/time v0.8.0
|
|
||||||
)
|
)
|
||||||
|
|
||||||
require (
|
require (
|
||||||
|
github.com/gofiber/schema v1.10.2 // indirect
|
||||||
|
github.com/gofiber/utils/v2 v2.6.5 // indirect
|
||||||
|
github.com/gofrs/uuid/v5 v5.5.1 // indirect
|
||||||
|
github.com/google/uuid v1.6.0 // indirect
|
||||||
github.com/inconshreveable/mousetrap v1.1.0 // indirect
|
github.com/inconshreveable/mousetrap v1.1.0 // indirect
|
||||||
github.com/justinmichaelvieira/iconv v0.1.0 // indirect
|
github.com/klauspost/compress v1.20.5 // indirect
|
||||||
github.com/labstack/gommon v0.4.2 // indirect
|
github.com/mattn/go-colorable v0.1.16 // indirect
|
||||||
github.com/mattn/go-colorable v0.1.13 // indirect
|
github.com/mattn/go-isatty v0.0.24 // indirect
|
||||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
github.com/molecule-man/go-brrr v1.3.1 // indirect
|
||||||
github.com/spf13/pflag v1.0.5 // indirect
|
github.com/philhofer/fwd v1.2.1 // indirect
|
||||||
|
github.com/spf13/pflag v1.1.0 // indirect
|
||||||
|
github.com/tinylib/msgp v1.6.5 // indirect
|
||||||
github.com/valyala/bytebufferpool v1.0.0 // indirect
|
github.com/valyala/bytebufferpool v1.0.0 // indirect
|
||||||
github.com/valyala/fasttemplate v1.2.2 // indirect
|
github.com/valyala/fasthttp v1.80.0 // indirect
|
||||||
golang.org/x/crypto v0.32.0 // indirect
|
golang.org/x/crypto v0.59.0 // indirect
|
||||||
golang.org/x/net v0.33.0 // indirect
|
golang.org/x/exp/typeparams v0.0.0-20231108232855-2478ac86f678 // indirect
|
||||||
golang.org/x/sys v0.29.0 // indirect
|
golang.org/x/mod v0.43.0 // indirect
|
||||||
golang.org/x/text v0.21.0 // indirect
|
golang.org/x/net v0.63.0 // indirect
|
||||||
|
golang.org/x/sys v0.50.0 // indirect
|
||||||
|
golang.org/x/telemetry v0.0.0-20261116191925-e77a43154acb // indirect
|
||||||
|
golang.org/x/tools v0.53.0 // indirect
|
||||||
|
golang.org/x/vuln v1.10.0 // indirect
|
||||||
|
honnef.co/go/tools v0.8.2 // indirect
|
||||||
|
)
|
||||||
|
|
||||||
|
tool (
|
||||||
|
golang.org/x/tools/cmd/goimports
|
||||||
|
golang.org/x/vuln/cmd/govulncheck
|
||||||
|
honnef.co/go/tools/cmd/staticcheck
|
||||||
)
|
)
|
||||||
@@ -1,109 +1,101 @@
|
|||||||
github.com/BurntSushi/toml v1.4.0 h1:kuoIxZQy2WRRk1pttg9asf+WVv6tWQuBNVmK8+nqPr0=
|
github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk=
|
||||||
github.com/BurntSushi/toml v1.4.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
|
github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
|
||||||
github.com/cpuguy83/go-md2man/v2 v2.0.4/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
|
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
|
||||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
github.com/fxamacker/cbor/v2 v2.10.0 h1:HVF3T5vYwLqO81ebPirWEPNv2SMrUMD3HLnKgEr6uWE=
|
||||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
github.com/fxamacker/cbor/v2 v2.10.0/go.mod h1:uSwlToFuT9BZAKRxxVm3qQC8DR4tlWl7D6pf20iRYH4=
|
||||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
github.com/getsentry/sentry-go v0.50.0 h1:gkO59rn/i0RCAXUUTflC5QVbTQGPXbaFabs2olVzc9g=
|
||||||
github.com/foize/go.fifo v0.0.0-20130327144150-3a04cfeec121 h1:4tcVl93sFQN4n6PYiJ6m11uypFWCpyybUpWV+HA7Fqg=
|
github.com/getsentry/sentry-go v0.50.0/go.mod h1:+xsDuN+SoRN/xfs1hdq78wnrE3omIZf+FCuh9FOW1C8=
|
||||||
github.com/foize/go.fifo v0.0.0-20130327144150-3a04cfeec121/go.mod h1:FnCzb+rCPKo7SBHmZYaSca9ymfnSHqh1E8jZz460/t0=
|
|
||||||
github.com/getsentry/sentry-go v0.31.1 h1:ELVc0h7gwyhnXHDouXkhqTFSO5oslsRDk0++eyE0KJ4=
|
|
||||||
github.com/getsentry/sentry-go v0.31.1/go.mod h1:CYNcMMz73YigoHljQRG+qPF+eMq8gG72XcGN/p71BAY=
|
|
||||||
github.com/getsentry/sentry-go/echo v0.31.1 h1:bGY2QrNq5PovERoQBwyfJtQixjptHC06gLiAlF0WUPc=
|
|
||||||
github.com/getsentry/sentry-go/echo v0.31.1/go.mod h1:2gHa20EVxDNNTJY+Cq4Eqr8A0Z6UEULh4ImSsVMSRUg=
|
|
||||||
github.com/go-errors/errors v1.4.2 h1:J6MZopCL4uSllY1OfXM374weqZFFItUbrImctkmUxIA=
|
github.com/go-errors/errors v1.4.2 h1:J6MZopCL4uSllY1OfXM374weqZFFItUbrImctkmUxIA=
|
||||||
github.com/go-errors/errors v1.4.2/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3BopGUQ5a5Og=
|
github.com/go-errors/errors v1.4.2/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3BopGUQ5a5Og=
|
||||||
github.com/golang-jwt/jwt/v5 v5.2.1 h1:OuVbFODueb089Lh128TAcimifWaLhJwVflnrgM17wHk=
|
github.com/gofiber/fiber/v3 v3.7.0 h1:aF+GfB7nP9Dd0wVsv6wmr8675v66OGfjSyoDhPmvKEo=
|
||||||
github.com/golang-jwt/jwt/v5 v5.2.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
|
github.com/gofiber/fiber/v3 v3.7.0/go.mod h1:7dlbpUZ789TJg4q/VfdS1UWDtB6Fl/Smk6ZYZusMpAQ=
|
||||||
github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
|
github.com/gofiber/schema v1.10.2 h1:mjqtglIvi/+NK3gJTra6wKOaBLZYx+tdNu7xtaCVPOg=
|
||||||
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
github.com/gofiber/schema v1.10.2/go.mod h1:scfpXbReJ8y9xKlNnrwlewJ8nIGVZZmzoHZ4i5yGxG0=
|
||||||
|
github.com/gofiber/utils/v2 v2.6.5 h1:rU+8ao6LKi3fKOA3sEjfLv1T+2C2IwomeVmEKaqkr4A=
|
||||||
|
github.com/gofiber/utils/v2 v2.6.5/go.mod h1:OqPxdhDW7fPz0dupDanqf4e5O15IyFKy724y/EY9RI4=
|
||||||
|
github.com/gofrs/uuid/v5 v5.5.1 h1:z1Ce19/JwNidXpy3tOQc3241lnJLKdKyq/xlNvlD4Ng=
|
||||||
|
github.com/gofrs/uuid/v5 v5.5.1/go.mod h1:bbAA98EoIlxyRHIVg6ektCSsZ5n8mSbwgEhvhMYlZgg=
|
||||||
|
github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
|
||||||
|
github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
|
||||||
|
github.com/google/go-cmdtest v0.4.1-0.20220921163831-55ab3332a786 h1:rcv+Ippz6RAtvaGgKxc+8FQIpxHgsF+HBzPyYL2cyVU=
|
||||||
|
github.com/google/go-cmdtest v0.4.1-0.20220921163831-55ab3332a786/go.mod h1:apVn/GCasLZUVpAJ6oWAuyP7Ne7CEsQbTnc0plM3m+o=
|
||||||
|
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||||
|
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||||
|
github.com/google/renameio v0.1.0 h1:GOZbcHa3HfsPKPlmyPyN2KEohoMXOhdMbHrvbpl2QaA=
|
||||||
|
github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI=
|
||||||
|
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||||
|
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||||
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
|
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
|
||||||
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
|
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
|
||||||
github.com/justinmichaelvieira/escpos v0.1.1 h1:FzvdSWbuR/6tVt6UKXPAxtS+VM7XGxLWUWb9EM49zvo=
|
github.com/klauspost/compress v1.20.5 h1:rJj5VjH4xQxbnLphg6eqUcDxRFCw1jpMdDY9qXlrwSs=
|
||||||
github.com/justinmichaelvieira/escpos v0.1.1/go.mod h1:BTLZkBKl4F53lYM/S635//HCltbEoUHuVfHHw+tC9os=
|
github.com/klauspost/compress v1.20.5/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
|
||||||
github.com/justinmichaelvieira/iconv v0.1.0 h1:nL7d7cHijfoBYHa804+5SvLwaWHO6+OFyJfWHrPnaOw=
|
github.com/liamg/tml v0.7.1 h1:k6lvZhowxUN0S/uAbgSLZ67wZtaTU+stAkpSNy+CbN0=
|
||||||
github.com/justinmichaelvieira/iconv v0.1.0/go.mod h1:Mm+28owXWTkJx2w+ftVX/RUnzWK7hM1hyUYkrgUerts=
|
github.com/liamg/tml v0.7.1/go.mod h1:Vuzs4Dn44Awoyd0MLl2EuJR++l1NlFqU6BJk0oxVYX4=
|
||||||
github.com/labstack/echo-jwt/v4 v4.3.0 h1:8JcvVCrK9dRkPx/aWY3ZempZLO336Bebh4oAtBcxAv4=
|
github.com/mattn/go-colorable v0.1.16 h1:+2YjeAe7xP1OQbZW1jERPWWCDLlNqFNCvjiqGiAt84A=
|
||||||
github.com/labstack/echo-jwt/v4 v4.3.0/go.mod h1:OlWm3wqfnq3Ma8DLmmH7GiEAz2S7Bj23im2iPMEAR+Q=
|
github.com/mattn/go-colorable v0.1.16/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
|
||||||
github.com/labstack/echo/v4 v4.13.3 h1:pwhpCPrTl5qry5HRdM5FwdXnhXSLSY+WE+YQSeCaafY=
|
github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI=
|
||||||
github.com/labstack/echo/v4 v4.13.3/go.mod h1:o90YNEeQWjDozo584l7AwhJMHN0bOC4tAfg+Xox9q5g=
|
github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A=
|
||||||
github.com/labstack/gommon v0.4.2 h1:F8qTUNXgG1+6WQmqoUWnz8WiEU60mXVVw0P4ht1WRA0=
|
github.com/molecule-man/go-brrr v1.3.1 h1:EwaJUzRIlp/dFmIpzq4J17CA5Zi5OHo2vOGmu09hF1w=
|
||||||
github.com/labstack/gommon v0.4.2/go.mod h1:QlUFxVM+SNXhDL/Z7YhocGIBYOiwB0mXm1+1bAPHPyU=
|
github.com/molecule-man/go-brrr v1.3.1/go.mod h1:7ybW6/7gA3oKY45jOfVNjSJDtrr6ea4tzbsTkjmQDC4=
|
||||||
github.com/liamg/tml v0.7.0 h1:0cVok661KuQy659aFpXpem8mXUDroREuWc1p/+y7hfU=
|
github.com/philhofer/fwd v1.2.1 h1:UtpS73q8bFgy/yH3gCq8LSNvj5gv/FowNOiWZa7uKwQ=
|
||||||
github.com/liamg/tml v0.7.0/go.mod h1:Vuzs4Dn44Awoyd0MLl2EuJR++l1NlFqU6BJk0oxVYX4=
|
github.com/philhofer/fwd v1.2.1/go.mod h1:RqIHx9QI14HlwKwm98g9Re5prTQ6LdeRQn+gXJFxsJM=
|
||||||
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
|
|
||||||
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
|
|
||||||
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
|
|
||||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
|
||||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
|
||||||
github.com/pingcap/errors v0.11.4 h1:lFuQV/oaUMGcD2tqt+01ROSmJs75VG1ToEOkZIZ4nE4=
|
github.com/pingcap/errors v0.11.4 h1:lFuQV/oaUMGcD2tqt+01ROSmJs75VG1ToEOkZIZ4nE4=
|
||||||
github.com/pingcap/errors v0.11.4/go.mod h1:Oi8TUi2kEtXXLMJk9l1cGmz20kV3TaQ0usTwv5KuLY8=
|
github.com/pingcap/errors v0.11.4/go.mod h1:Oi8TUi2kEtXXLMJk9l1cGmz20kV3TaQ0usTwv5KuLY8=
|
||||||
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
|
||||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
|
||||||
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
||||||
github.com/spf13/cobra v1.8.1 h1:e5/vxKd/rZsfSJMUX1agtjeTDf+qv1/JdBF8gg5k9ZM=
|
github.com/shamaton/msgpack/v3 v3.2.7 h1:YuVYjZq5+NLIREdW52txCmEfVGIi4ithcdhOJhAmU5A=
|
||||||
github.com/spf13/cobra v1.8.1/go.mod h1:wHxEcudfqmLYa8iTfL+OuZPbBZkmvliBWKIezN3kD9Y=
|
github.com/shamaton/msgpack/v3 v3.2.7/go.mod h1:sgBYvEiyz8JR1NC3yGRoPVME9xXovpnh3l/plW1nfRo=
|
||||||
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
|
github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=
|
||||||
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4=
|
||||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
github.com/spf13/pflag v1.1.0 h1:6W6MbVUrnMb8PEhjkqwsVLY7ryuzRfFHF4mQd7L94ag=
|
||||||
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
github.com/spf13/pflag v1.1.0/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||||
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
|
||||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
|
||||||
github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
github.com/tinylib/msgp v1.6.5 h1:iAH6XTP7BpzErjBZlujJQXxA+GmRi2YWs6M4KdLtNbE=
|
||||||
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
|
github.com/tinylib/msgp v1.6.5/go.mod h1:RSp0LW9oSxFut3KzESt5Voq4GVWyS+PSulT77roAqEA=
|
||||||
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
|
||||||
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
|
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
|
||||||
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
|
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
|
||||||
github.com/valyala/fasttemplate v1.2.2 h1:lxLXG0uE3Qnshl9QyaK6XJxMXlQZELvChBOCmQD0Loo=
|
github.com/valyala/fasthttp v1.80.0 h1:10pVr/QLFGbSX8ikDS0i+wOi2AGY2Sy0TACVpoiG+7U=
|
||||||
github.com/valyala/fasttemplate v1.2.2/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ=
|
github.com/valyala/fasthttp v1.80.0/go.mod h1:oulvtxx5dQeORu6sKWaJItcnWXRqiGmrTFQ4gmZjLFM=
|
||||||
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
|
github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM=
|
||||||
|
github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg=
|
||||||
|
go.jetify.com/typeid v1.3.0 h1:fuWV7oxO4mSsgpxwhaVpFXgt0IfjogR29p+XAjDCVKY=
|
||||||
|
go.jetify.com/typeid v1.3.0/go.mod h1:CtVGyt2+TSp4Rq5+ARLvGsJqdNypKBAC6INQ9TLPlmk=
|
||||||
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
|
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
|
||||||
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
|
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
|
||||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
|
||||||
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
go.yaml.in/yaml/v3 v3.0.6 h1:zcDfvjXEqTQmpjniUBLc91xYJMB2c4QOFxEF/LCEckM=
|
||||||
golang.org/x/crypto v0.32.0 h1:euUpcYgM8WcP71gNpTqQCn6rC2t6ULUPiOzfWaXVVfc=
|
go.yaml.in/yaml/v3 v3.0.6/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
|
||||||
golang.org/x/crypto v0.32.0/go.mod h1:ZnnJkOaASj8g0AjIduWNlq2NRxL0PlBrbKVyZ6V/Ugc=
|
golang.org/x/crypto v0.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c=
|
||||||
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
|
golang.org/x/crypto v0.59.0/go.mod h1:veDyUwATGs3c+vN3VfTbzViMGXeTBk3WyhBOkn+F/4U=
|
||||||
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
golang.org/x/exp/typeparams v0.0.0-20231108232855-2478ac86f678 h1:1P7xPZEwZMoBoz0Yze5Nx2/4pxj6nw9ZqHWXqP0iRgQ=
|
||||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
golang.org/x/exp/typeparams v0.0.0-20231108232855-2478ac86f678/go.mod h1:AbB0pIl9nAr9wVwH+Z2ZpaocVmF5I4GyWCDIsVjR0bk=
|
||||||
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
golang.org/x/image v0.48.0 h1:1AvuPcuoOTJpA7s4VZ5umrb90T3So0rkB/bSGmxkxik=
|
||||||
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
|
golang.org/x/image v0.48.0/go.mod h1:mmtg64iqJKGqEgy+r13dfybl85tmxUd2lMnmaiSdWYY=
|
||||||
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
|
golang.org/x/mod v0.43.0 h1:MFuq5J6s35W9D3IjkwyWc9vHh0nENOrt5K8Iof4ofmg=
|
||||||
golang.org/x/net v0.33.0 h1:74SYHlV8BIgHIFC/LrYkOGIwL19eTYXQ5wc6TBuO36I=
|
golang.org/x/mod v0.43.0/go.mod h1:4ec1JnuyBz5+FIVhg86UsA39YG8BpnrZdJYSNHmGzHY=
|
||||||
golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4=
|
golang.org/x/net v0.63.0 h1:HCoTmNh9EpD1PpK8gBNFY4gcTY4N+KQEO8ylfIKqFJ0=
|
||||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
golang.org/x/net v0.63.0/go.mod h1:15JLg3IX1bLjHK264EZQEbIpTiR/KVLuo9CTRWd0pig=
|
||||||
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
golang.org/x/sync v0.25.0 h1:dJnifr0nMV8/SBnBvdo4eSGGnrc3O4FFx6IqvtLcmRs=
|
||||||
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
golang.org/x/sync v0.25.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
|
||||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs=
|
||||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||||
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/telemetry v0.0.0-20261116191925-e77a43154acb h1:juaHO1dWannznOvpnfdTIjkqPDBsG9OcdkOBTBlcUCA=
|
||||||
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/telemetry v0.0.0-20261116191925-e77a43154acb/go.mod h1:frnW8knEsfI9dILitAKHe8/iQ1ycXgpvIjQ/xz9QFYk=
|
||||||
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/text v0.44.0 h1:YItdp/mQNGnsmrgpcdA5yQ3bnRxCfo/Tj/iByGW9GGo=
|
||||||
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/text v0.44.0/go.mod h1:S4FR1waQ9LbjQTls97SyRjDaUUVkaM+cXwwuG/G+MwY=
|
||||||
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/tools v0.53.0 h1:T3bIVp3zjHG9/aEiFk6BXxFh5/Vcbk7JA5hRq1cG8IU=
|
||||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/tools v0.53.0/go.mod h1:vg+Vrb7y5mTTtxZLTdbTK8G745wcaLcsCtgCWgQONCI=
|
||||||
golang.org/x/sys v0.29.0 h1:TPYlXGxvx1MGTn2GiZDhnjPA9wZzZeGKHHmKhHYvgaU=
|
golang.org/x/tools/go/expect v0.1.1-deprecated h1:jpBZDwmgPhXsKZC6WhL20P4b/wmnpsEAGHaNy0n/rJM=
|
||||||
golang.org/x/sys v0.29.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
golang.org/x/tools/go/expect v0.1.1-deprecated/go.mod h1:eihoPOH+FgIqa3FpoTwguz/bVUSGBlGQU67vpBeOrBY=
|
||||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
golang.org/x/tools/go/packages/packagestest v0.1.1-deprecated h1:1h2MnaIAIXISqTFKdENegdpAgUXz6NrPEsbIeWaBRvM=
|
||||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
golang.org/x/tools/go/packages/packagestest v0.1.1-deprecated/go.mod h1:RVAQXBGNv1ib0J382/DPCRS/BPnsGebyM1Gj5VSDpG8=
|
||||||
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
|
golang.org/x/vuln v1.10.0 h1:W/Im35AGknunDiqBysVe9VoMfaeTJE7lptrD+1s//aE=
|
||||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
golang.org/x/vuln v1.10.0/go.mod h1:kNpckBWtSQiR+USd0ZgdhJCCWf/ZXOl1+n3Wybcj8eE=
|
||||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
|
||||||
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
|
||||||
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
|
||||||
golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
|
|
||||||
golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo=
|
|
||||||
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
|
|
||||||
golang.org/x/time v0.8.0 h1:9i3RxcPv3PZnitoVGMPDKZSq1xW1gK1Xy3ArNOGZfEg=
|
|
||||||
golang.org/x/time v0.8.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM=
|
|
||||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
|
||||||
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
|
||||||
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
|
|
||||||
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
|
|
||||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
|
||||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
|
||||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
|
||||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
honnef.co/go/tools v0.8.2 h1:+jPbCzuYxYrcoOvCecYUFDj+XJQRmzIhJmlbpps21Zk=
|
||||||
|
honnef.co/go/tools v0.8.2/go.mod h1:xG1Q4n+mg3bKZrO6RWFA9jFlkqplflmDRHGeuexiLDs=
|
||||||
+156
-137
@@ -1,52 +1,141 @@
|
|||||||
#!/bin/bash
|
#!/bin/bash
|
||||||
set -e
|
# Installs Überbringer behind nginx with a Let's Encrypt certificate.
|
||||||
|
#
|
||||||
|
# Usage: sudo ./install.sh <domain> <acme-email> <printer-address>
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
DOMAIN=$1
|
DOMAIN="${1:-}"
|
||||||
ACME_EMAIL=$2
|
ACME_EMAIL="${2:-}"
|
||||||
|
PRINTER_ADDRESS="${3:-}"
|
||||||
|
|
||||||
|
LOG=/var/log/uberbringer-install.log
|
||||||
|
CONFIG_DIR=/etc/uberbringer
|
||||||
|
BIN=/usr/local/bin/uberbringer
|
||||||
|
SERVICE_USER=uberbringer
|
||||||
|
RELEASE_URL=https://git.anomalous.dev/57_Wolve/uberbringer/releases/download/latest
|
||||||
|
|
||||||
if [[ "$EUID" -ne 0 ]]; then
|
if [[ "$EUID" -ne 0 ]]; then
|
||||||
echo -e "\e[31m[FATAL]\e[39m Currently this script requires being ran as root user - please try again as root."
|
echo -e "\e[31m[FATAL]\e[39m This script must be run as root."
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
|
|
||||||
echo -e "\n\nINSTALL LOG FOR Uberbringer: $(date --rfc-3339=seconds)\n" >> /var/log/uberbringer-install.log
|
if [[ -z "$DOMAIN" || -z "$ACME_EMAIL" || -z "$PRINTER_ADDRESS" ]]; then
|
||||||
|
echo "Usage: $0 <domain> <acme-email> <printer-address>"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo -e "\n\nINSTALL LOG FOR Uberbringer: $(date --rfc-3339=seconds)\n" >> "$LOG"
|
||||||
|
|
||||||
info() {
|
info() {
|
||||||
echo -e "\e[34m[INFO]\e[39m $1"
|
echo -e "\e[34m[INFO]\e[39m $1"
|
||||||
echo "[INFO] $1" >> /var/log/uberbringer-install.log
|
echo "[INFO] $1" >> "$LOG"
|
||||||
}
|
}
|
||||||
|
|
||||||
debug() {
|
debug() {
|
||||||
if [[ ! -z "$DEBUG" ]]; then
|
if [[ -n "${DEBUG:-}" ]]; then
|
||||||
echo -e "\e[96m[DEBUG]\e[39m $1"
|
echo -e "\e[96m[DEBUG]\e[39m $1"
|
||||||
fi
|
fi
|
||||||
echo "[DEBUG] $1" >> /var/log/uberbringer-install.log
|
echo "[DEBUG] $1" >> "$LOG"
|
||||||
}
|
|
||||||
|
|
||||||
warn() {
|
|
||||||
echo -e "\e[33m[WARNING]\e[39m $1"
|
|
||||||
echo "[WARNING] $1" >> /var/log/uberbringer-install.log
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fatal() {
|
fatal() {
|
||||||
echo -e "\e[31m[FATAL]\e[39m $1"
|
echo -e "\e[31m[FATAL]\e[39m $1"
|
||||||
echo "[FATAL] $1" >> /var/log/uberbringer-install.log
|
echo "[FATAL] $1" >> "$LOG"
|
||||||
exit 1
|
exit 1
|
||||||
}
|
}
|
||||||
|
|
||||||
create_jwt(){
|
require() {
|
||||||
jwt_header=$(echo -n '{"alg":"HS256","typ":"JWT"}' | base64 | sed s/\+/-/g | sed 's/\//_/g' | sed -E s/=+$//)
|
command -v "$1" > /dev/null 2>&1 || fatal "Couldn't find $1 - please install it and rerun the script."
|
||||||
payload=$(echo -n '{"user_id":"uberbringer"}' | base64 | sed s/\+/-/g |sed 's/\//_/g' | sed -E s/=+$//)
|
|
||||||
secret=$(openssl rand -base64 32)
|
|
||||||
hexsecret=$(echo -n "$secret" | xxd -p | paste -sd "")
|
|
||||||
hmac_signature=$(echo -n "${jwt_header}.${payload}" | openssl dgst -sha256 -mac HMAC -macopt hexkey:$hexsecret -binary | base64 | sed s/\+/-/g | sed 's/\//_/g' | sed -E s/=+$//)
|
|
||||||
JWT_TOKEN="${jwt_header}.${payload}.${hmac_signature}"
|
|
||||||
}
|
}
|
||||||
|
|
||||||
install_nginx(){
|
detect_arch() {
|
||||||
info "Installing nginx..."
|
case "$(uname -m)" in
|
||||||
|
x86_64) echo "amd64" ;;
|
||||||
|
aarch64 | arm64) echo "arm64" ;;
|
||||||
|
armv7l) echo "armv7" ;;
|
||||||
|
armv6l) echo "armv6" ;;
|
||||||
|
*) fatal "Unsupported architecture: $(uname -m)" ;;
|
||||||
|
esac
|
||||||
|
}
|
||||||
|
|
||||||
mkdir -p /etc/nginx/includes
|
install_uberbringer_binary() {
|
||||||
|
local arch archive tmp
|
||||||
|
arch="$(detect_arch)"
|
||||||
|
archive="uberbringer_linux_${arch}.tar"
|
||||||
|
tmp="$(mktemp -d)"
|
||||||
|
trap 'rm -rf "$tmp"' RETURN
|
||||||
|
|
||||||
|
info "Downloading ${archive}..."
|
||||||
|
curl -fsSL -o "$tmp/$archive" "$RELEASE_URL/$archive"
|
||||||
|
tar -xf "$tmp/$archive" -C "$tmp"
|
||||||
|
install -m 0755 "$tmp/uberbringer" "$BIN"
|
||||||
|
}
|
||||||
|
|
||||||
|
create_service_user() {
|
||||||
|
if ! id "$SERVICE_USER" > /dev/null 2>&1; then
|
||||||
|
info "Creating system user $SERVICE_USER..."
|
||||||
|
useradd --system --no-create-home --shell /usr/sbin/nologin "$SERVICE_USER"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
write_config() {
|
||||||
|
mkdir -p "$CONFIG_DIR"
|
||||||
|
if [[ -f "$CONFIG_DIR/config.toml" ]]; then
|
||||||
|
info "Keeping existing $CONFIG_DIR/config.toml"
|
||||||
|
return
|
||||||
|
fi
|
||||||
|
info "Creating Uberbringer config..."
|
||||||
|
local secret
|
||||||
|
secret="$("$BIN" secret)"
|
||||||
|
cat <<EOT > "$CONFIG_DIR/config.toml"
|
||||||
|
[webserver]
|
||||||
|
bind_ip = "127.0.0.1"
|
||||||
|
port = 8080
|
||||||
|
|
||||||
|
[api]
|
||||||
|
secret = "$secret"
|
||||||
|
|
||||||
|
[printer]
|
||||||
|
address = "$PRINTER_ADDRESS"
|
||||||
|
EOT
|
||||||
|
chown root:"$SERVICE_USER" "$CONFIG_DIR/config.toml"
|
||||||
|
chmod 0640 "$CONFIG_DIR/config.toml"
|
||||||
|
}
|
||||||
|
|
||||||
|
install_service() {
|
||||||
|
info "Creating uberbringer.service..."
|
||||||
|
cat <<EOT > /etc/systemd/system/uberbringer.service
|
||||||
|
[Unit]
|
||||||
|
Description=Uberbringer Daemon
|
||||||
|
Wants=network-online.target
|
||||||
|
After=network.target network-online.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
User=$SERVICE_USER
|
||||||
|
Group=$SERVICE_USER
|
||||||
|
WorkingDirectory=$CONFIG_DIR
|
||||||
|
ExecStart=$BIN --config $CONFIG_DIR/config.toml
|
||||||
|
Restart=on-failure
|
||||||
|
RestartSec=5
|
||||||
|
LimitNOFILE=4096
|
||||||
|
NoNewPrivileges=true
|
||||||
|
ProtectSystem=strict
|
||||||
|
ProtectHome=true
|
||||||
|
PrivateTmp=true
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
|
EOT
|
||||||
|
|
||||||
|
systemctl daemon-reload
|
||||||
|
systemctl enable uberbringer
|
||||||
|
debug "Starting Uberbringer Web Service..."
|
||||||
|
systemctl restart uberbringer
|
||||||
|
}
|
||||||
|
|
||||||
|
install_nginx() {
|
||||||
|
info "Configuring nginx..."
|
||||||
|
mkdir -p /etc/nginx/includes "/var/www/$DOMAIN"
|
||||||
|
|
||||||
cat <<EOT > /etc/nginx/includes/letsencrypt-webroot
|
cat <<EOT > /etc/nginx/includes/letsencrypt-webroot
|
||||||
location / {
|
location / {
|
||||||
@@ -54,8 +143,7 @@ location / {
|
|||||||
}
|
}
|
||||||
EOT
|
EOT
|
||||||
|
|
||||||
rm /etc/nginx/sites-enabled/default || true
|
rm -f /etc/nginx/sites-enabled/default /etc/nginx/sites-available/default
|
||||||
rm /etc/nginx/sites-available/default || true
|
|
||||||
|
|
||||||
cat <<EOT > /etc/nginx/sites-available/default.conf
|
cat <<EOT > /etc/nginx/sites-available/default.conf
|
||||||
server {
|
server {
|
||||||
@@ -67,157 +155,88 @@ server {
|
|||||||
}
|
}
|
||||||
EOT
|
EOT
|
||||||
|
|
||||||
ln -s /etc/nginx/sites-available/default.conf /etc/nginx/sites-enabled/default.conf || true
|
ln -sf /etc/nginx/sites-available/default.conf /etc/nginx/sites-enabled/default.conf
|
||||||
|
|
||||||
systemctl enable nginx
|
systemctl enable nginx
|
||||||
|
|
||||||
debug "Starting Nginx..."
|
debug "Starting Nginx..."
|
||||||
systemctl restart nginx
|
systemctl restart nginx
|
||||||
}
|
}
|
||||||
|
|
||||||
install_acmesh() {
|
install_acmesh() {
|
||||||
mkdir -p /etc/letsencrypt/live/$DOMAIN > /dev/null 2>&1
|
mkdir -p "/etc/letsencrypt/live/$DOMAIN"
|
||||||
|
|
||||||
info "Installing Acme.sh..."
|
info "Installing acme.sh..."
|
||||||
curl https://get.acme.sh | sh -s email=$ACME_EMAIL
|
curl -fsSL https://get.acme.sh | sh -s email="$ACME_EMAIL"
|
||||||
|
|
||||||
info "Issuing SSL Certificate..."
|
info "Issuing SSL certificate..."
|
||||||
/root/.acme.sh/acme.sh --issue -w /var/www/$DOMAIN --keypath /etc/letsencrypt/live/$DOMAIN/privkey.pem --fullchainpath /etc/letsencrypt/live/$DOMAIN/fullchain.pem -d $DOMAIN --reloadcmd "systemctl restart nginx" --force
|
/root/.acme.sh/acme.sh --issue -w "/var/www/$DOMAIN" \
|
||||||
|
--keypath "/etc/letsencrypt/live/$DOMAIN/privkey.pem" \
|
||||||
|
--fullchainpath "/etc/letsencrypt/live/$DOMAIN/fullchain.pem" \
|
||||||
|
-d "$DOMAIN" --reloadcmd "systemctl reload nginx" --force
|
||||||
|
|
||||||
info "Enabling Acme.sh Automatic Upgrade..."
|
info "Enabling acme.sh automatic upgrade..."
|
||||||
/root/.acme.sh/acme.sh --upgrade --auto-upgrade || true
|
/root/.acme.sh/acme.sh --upgrade --auto-upgrade || true
|
||||||
|
|
||||||
cat <<EOT > /etc/nginx/sites-available/reverse-proxy.conf
|
cat <<EOT > /etc/nginx/sites-available/reverse-proxy.conf
|
||||||
server {
|
server {
|
||||||
listen 443;
|
listen 443 ssl;
|
||||||
listen [::]:443;
|
listen [::]:443 ssl;
|
||||||
server_name $DOMAIN;
|
server_name $DOMAIN;
|
||||||
|
|
||||||
ssl on;
|
|
||||||
ssl_certificate /etc/letsencrypt/live/$DOMAIN/fullchain.pem;
|
ssl_certificate /etc/letsencrypt/live/$DOMAIN/fullchain.pem;
|
||||||
ssl_certificate_key /etc/letsencrypt/live/$DOMAIN/privkey.pem;
|
ssl_certificate_key /etc/letsencrypt/live/$DOMAIN/privkey.pem;
|
||||||
ssl_session_cache builtin:1000 shared:SSL:10m;
|
ssl_session_cache shared:SSL:10m;
|
||||||
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
|
ssl_protocols TLSv1.2 TLSv1.3;
|
||||||
ssl_ciphers 'EECDH+AES128:EECDH+AES256:+SHA:DHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA:RSA+3DES:!DSS';
|
ssl_prefer_server_ciphers off;
|
||||||
ssl_prefer_server_ciphers on;
|
|
||||||
|
|
||||||
# Set the access log location
|
error_log /var/log/nginx/uberbringer_error.log;
|
||||||
error_log /var/log/nginx/default_error.log;
|
access_log /var/log/nginx/uberbringer_access.log;
|
||||||
access_log /var/log/nginx/default_access.log;
|
|
||||||
|
client_max_body_size 4m;
|
||||||
|
|
||||||
location / {
|
location / {
|
||||||
|
|
||||||
# Set the proxy headers
|
|
||||||
proxy_redirect off;
|
proxy_redirect off;
|
||||||
proxy_pass_request_headers on;
|
|
||||||
proxy_set_header Upgrade \$http_upgrade;
|
|
||||||
proxy_set_header Connection "upgrade";
|
|
||||||
proxy_set_header Host \$http_host;
|
proxy_set_header Host \$http_host;
|
||||||
proxy_set_header Referer \$http_referer;
|
# Uberbringer trusts X-Real-IP from 127.0.0.1 for per-client rate limits.
|
||||||
|
proxy_set_header X-Real-IP \$remote_addr;
|
||||||
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
|
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
|
||||||
proxy_set_header X-Forwarded-Proto \$scheme;
|
proxy_set_header X-Forwarded-Proto \$scheme;
|
||||||
|
|
||||||
# Configure which address the request is proxied to
|
proxy_pass http://127.0.0.1:8080;
|
||||||
proxy_pass http://127.0.0.1:8080/;
|
proxy_read_timeout 90;
|
||||||
proxy_read_timeout 90;
|
|
||||||
|
|
||||||
# Security headers
|
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
|
||||||
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload";
|
add_header X-Frame-Options DENY always;
|
||||||
add_header X-Frame-Options DENY;
|
add_header X-Content-Type-Options nosniff always;
|
||||||
add_header X-Content-Type-Options nosniff;
|
add_header Referrer-Policy "no-referrer" always;
|
||||||
add_header X-XSS-Protection "1; mode=block";
|
|
||||||
add_header Referrer-Policy "origin";
|
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
EOT
|
EOT
|
||||||
|
|
||||||
ln -s /etc/nginx/sites-available/reverse-proxy.conf /etc/nginx/sites-enabled/reverse-proxy.conf || true
|
ln -sf /etc/nginx/sites-available/reverse-proxy.conf /etc/nginx/sites-enabled/reverse-proxy.conf
|
||||||
|
nginx -t
|
||||||
debug "Restarting Nginx..."
|
debug "Reloading Nginx..."
|
||||||
systemctl restart nginx > /dev/null 2>&1
|
systemctl reload nginx
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
install_uberbringer(){
|
|
||||||
info "Installing Uberbringer web service..."
|
|
||||||
mkdir -p /etc/uberbringer > /dev/null 2>&1
|
|
||||||
|
|
||||||
info "Creating Uberbringer config..."
|
|
||||||
cat <<EOT > /etc/uberbringer/config.toml
|
|
||||||
[webserver]
|
|
||||||
bind_ip = "127.0.0.1"
|
|
||||||
port = 8080
|
|
||||||
|
|
||||||
[api]
|
|
||||||
secret = "$secret"
|
|
||||||
EOT
|
|
||||||
|
|
||||||
info "Downloading uberbringer_linux_amd64..."
|
|
||||||
wget -O uberbringer_linux_amd64.tar https://git.anomalous.dev/57_Wolve/uberbringer/releases/download/latest/uberbringer_linux_amd64.tar || true
|
|
||||||
|
|
||||||
tar xvf uberbringer_linux_amd64.tar -C /usr/local/bin/
|
|
||||||
|
|
||||||
rm uberbringer_linux_amd64.tar.gz > /dev/null 2>&1 || true
|
|
||||||
|
|
||||||
chmod u+x /usr/local/bin/uberbringer
|
|
||||||
|
|
||||||
info "Creating uberbringer.service..."
|
|
||||||
cat <<EOT > /etc/systemd/system/uberbringer.service
|
|
||||||
[Unit]
|
|
||||||
Description=Uberbringer Daemon
|
|
||||||
Wants=network-online.target
|
|
||||||
After=network.target network-online.target
|
|
||||||
|
|
||||||
[Service]
|
|
||||||
User=root
|
|
||||||
WorkingDirectory=/etc/uberbringer
|
|
||||||
LimitNOFILE=4096
|
|
||||||
PIDFile=/var/run/uberbringer/daemon.pid
|
|
||||||
ExecStart=/usr/local/bin/uberbringer
|
|
||||||
Restart=on-failure
|
|
||||||
StartLimitInterval=600
|
|
||||||
|
|
||||||
[Install]
|
|
||||||
WantedBy=multi-user.target
|
|
||||||
EOT
|
|
||||||
|
|
||||||
systemctl daemon-reload > /dev/null 2>&1 || true
|
|
||||||
systemctl enable uberbringer > /dev/null 2>&1 || true
|
|
||||||
|
|
||||||
debug "Starting Uberbringer Web Service..."
|
|
||||||
systemctl start uberbringer > /dev/null 2>&1 || true
|
|
||||||
}
|
}
|
||||||
|
|
||||||
main() {
|
main() {
|
||||||
info "Script loaded, starting the install process..."
|
info "Script loaded, starting the install process..."
|
||||||
|
|
||||||
info "Installing curl, socat, xxd, and nginx..."
|
info "Installing curl, socat and nginx..."
|
||||||
apt install -y nginx curl openssl xxd socat > /dev/null 2>&1
|
apt-get install -y nginx curl socat > /dev/null 2>&1
|
||||||
|
|
||||||
if [[ ! -x "$(command -v nginx)" ]]; then
|
require nginx
|
||||||
fatal "Couldn't find curl installed on the system - please install it first and rerun the script."
|
require curl
|
||||||
fi
|
require socat
|
||||||
|
|
||||||
if [[ ! -x "$(command -v openssl)" ]]; then
|
install_uberbringer_binary
|
||||||
fatal "Couldn't find openssl installed on the system - please install it first and rerun the script."
|
create_service_user
|
||||||
fi
|
write_config
|
||||||
|
install_service
|
||||||
if [[ ! -x "$(command -v curl)" ]]; then
|
|
||||||
fatal "Couldn't find curl installed on the system - please install it first and rerun the script."
|
|
||||||
fi
|
|
||||||
|
|
||||||
if [[ ! -x "$(command -v socat)" ]]; then
|
|
||||||
fatal "Couldn't find socat installed on the system - please install it first and rerun the script."
|
|
||||||
fi
|
|
||||||
|
|
||||||
create_jwt
|
|
||||||
install_nginx
|
install_nginx
|
||||||
install_acmesh
|
install_acmesh
|
||||||
install_uberbringer
|
|
||||||
|
|
||||||
info "Uberbringer Service is now installed, install script finished."
|
info "Uberbringer service is now installed."
|
||||||
echo -e "\e[34m[INFO]\e[39m API Token: $JWT_TOKEN"
|
echo -e "\e[34m[INFO]\e[39m API token: $("$BIN" token --config "$CONFIG_DIR/config.toml")"
|
||||||
}
|
}
|
||||||
|
|
||||||
main
|
main
|
||||||
@@ -0,0 +1,165 @@
|
|||||||
|
// Package uberbringer wires the Überbringer daemon together and provides its
|
||||||
|
// command-line interface.
|
||||||
|
package uberbringer
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/rand"
|
||||||
|
"encoding/base64"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/golang-jwt/jwt/v5"
|
||||||
|
"github.com/liamg/tml"
|
||||||
|
"github.com/spf13/cobra"
|
||||||
|
|
||||||
|
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/config"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Project information shown by the banner, the version command and the API
|
||||||
|
// index route.
|
||||||
|
const (
|
||||||
|
Project = "Überbringer"
|
||||||
|
Description = "EPSON Receipt Printer Server"
|
||||||
|
Authors = "https://git.anomalous.dev/57_Wolve/uberbringer"
|
||||||
|
copyright = "William Gill"
|
||||||
|
)
|
||||||
|
|
||||||
|
// secretBytes is the size of generated API secrets: 256 bits, the HS256 hash
|
||||||
|
// size.
|
||||||
|
const secretBytes = 32
|
||||||
|
|
||||||
|
// BuildInfo is injected at build time through -ldflags.
|
||||||
|
type BuildInfo struct {
|
||||||
|
Version string
|
||||||
|
Commit string
|
||||||
|
|
||||||
|
// SentryDSN is the default DSN for release builds; sentry.dsn in the
|
||||||
|
// config and the SENTRY_DSN environment variable take precedence.
|
||||||
|
SentryDSN string
|
||||||
|
}
|
||||||
|
|
||||||
|
// Execute runs the command line given by args.
|
||||||
|
func Execute(ctx context.Context, build BuildInfo, args []string) error {
|
||||||
|
root := newRootCommand(build)
|
||||||
|
root.SetArgs(args)
|
||||||
|
return root.ExecuteContext(ctx)
|
||||||
|
}
|
||||||
|
|
||||||
|
func newRootCommand(build BuildInfo) *cobra.Command {
|
||||||
|
var configPath string
|
||||||
|
root := &cobra.Command{
|
||||||
|
Use: "uberbringer",
|
||||||
|
Short: "Runs the Überbringer receipt printer daemon.",
|
||||||
|
SilenceUsage: true,
|
||||||
|
SilenceErrors: true,
|
||||||
|
Args: cobra.NoArgs,
|
||||||
|
RunE: func(cmd *cobra.Command, _ []string) error {
|
||||||
|
return serve(cmd.Context(), configPath, build, cmd.OutOrStdout())
|
||||||
|
},
|
||||||
|
}
|
||||||
|
root.PersistentFlags().StringVarP(&configPath, "config", "c", "config.toml", "path to the daemon config file")
|
||||||
|
root.AddCommand(
|
||||||
|
newVersionCommand(build),
|
||||||
|
newSecretCommand(),
|
||||||
|
newTokenCommand(&configPath),
|
||||||
|
)
|
||||||
|
return root
|
||||||
|
}
|
||||||
|
|
||||||
|
func newVersionCommand(build BuildInfo) *cobra.Command {
|
||||||
|
return &cobra.Command{
|
||||||
|
Use: "version",
|
||||||
|
Short: "Prints the version and exits.",
|
||||||
|
Args: cobra.NoArgs,
|
||||||
|
RunE: func(cmd *cobra.Command, _ []string) error {
|
||||||
|
_, err := fmt.Fprintln(cmd.OutOrStdout(), versionLine(build))
|
||||||
|
return err
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func newSecretCommand() *cobra.Command {
|
||||||
|
return &cobra.Command{
|
||||||
|
Use: "secret",
|
||||||
|
Short: "Prints a new random API secret for api.secret in the config.",
|
||||||
|
Args: cobra.NoArgs,
|
||||||
|
RunE: func(cmd *cobra.Command, _ []string) error {
|
||||||
|
_, err := fmt.Fprintln(cmd.OutOrStdout(), newSecret())
|
||||||
|
return err
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func newTokenCommand(configPath *string) *cobra.Command {
|
||||||
|
var (
|
||||||
|
subject string
|
||||||
|
ttl time.Duration
|
||||||
|
)
|
||||||
|
cmd := &cobra.Command{
|
||||||
|
Use: "token",
|
||||||
|
Short: "Prints a bearer token signed with the config's api.secret.",
|
||||||
|
Args: cobra.NoArgs,
|
||||||
|
RunE: func(cmd *cobra.Command, _ []string) error {
|
||||||
|
cfg, err := config.Load(*configPath)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
token, err := signToken([]byte(cfg.API.Secret), subject, ttl, time.Now())
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
_, err = fmt.Fprintln(cmd.OutOrStdout(), token)
|
||||||
|
return err
|
||||||
|
},
|
||||||
|
}
|
||||||
|
cmd.Flags().StringVar(&subject, "subject", "uberbringer", "token subject, e.g. the client's name")
|
||||||
|
cmd.Flags().DurationVar(&ttl, "ttl", 0, "token lifetime, e.g. 720h (0 means it never expires)")
|
||||||
|
return cmd
|
||||||
|
}
|
||||||
|
|
||||||
|
// newSecret returns a random base64 API secret. crypto/rand.Read never fails
|
||||||
|
// on supported platforms; it crashes the program rather than return weak bytes.
|
||||||
|
func newSecret() string {
|
||||||
|
b := make([]byte, secretBytes)
|
||||||
|
_, _ = rand.Read(b) // documented to never return an error
|
||||||
|
return base64.StdEncoding.EncodeToString(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
// signToken returns an HS256 JWT for subject. A zero ttl means no expiry.
|
||||||
|
func signToken(secret []byte, subject string, ttl time.Duration, now time.Time) (string, error) {
|
||||||
|
if ttl < 0 {
|
||||||
|
return "", fmt.Errorf("ttl must not be negative")
|
||||||
|
}
|
||||||
|
claims := jwt.RegisteredClaims{
|
||||||
|
Subject: subject,
|
||||||
|
IssuedAt: jwt.NewNumericDate(now),
|
||||||
|
}
|
||||||
|
if ttl > 0 {
|
||||||
|
claims.ExpiresAt = jwt.NewNumericDate(now.Add(ttl))
|
||||||
|
}
|
||||||
|
signed, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString(secret)
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("signing token: %w", err)
|
||||||
|
}
|
||||||
|
return signed, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func versionLine(build BuildInfo) string {
|
||||||
|
return fmt.Sprintf("%s | Version: %s Build: %s | Copyright © %d %s",
|
||||||
|
Project, build.Version, build.Commit, time.Now().Year(), copyright)
|
||||||
|
}
|
||||||
|
|
||||||
|
// printBanner writes the startup banner.
|
||||||
|
func printBanner(w io.Writer, build BuildInfo) {
|
||||||
|
const rule = "-----------------------------------------------------------------------------------------------"
|
||||||
|
// The banner is cosmetic; a failed write to the terminal is not worth
|
||||||
|
// stopping the daemon for.
|
||||||
|
_ = tml.Fprintf(w, "%s\n\n", rule)
|
||||||
|
_ = tml.Fprintf(w, "<bold> <lightblue>%s</lightblue></bold>\n\n", versionLine(build))
|
||||||
|
_ = tml.Fprintf(w, "<bold> <lightblue>Project:</lightblue> %s</bold>\n", Project)
|
||||||
|
_ = tml.Fprintf(w, "<bold> <lightblue>Description:</lightblue> %s</bold>\n", Description)
|
||||||
|
_ = tml.Fprintf(w, "<bold> <lightblue>Authors:</lightblue> %s</bold>\n\n", Authors)
|
||||||
|
_ = tml.Fprintf(w, "%s\n", rule)
|
||||||
|
}
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
package uberbringer
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/base64"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/golang-jwt/jwt/v5"
|
||||||
|
)
|
||||||
|
|
||||||
|
func runCommand(t *testing.T, args ...string) (string, error) {
|
||||||
|
t.Helper()
|
||||||
|
cmd := newRootCommand(BuildInfo{Version: "1.2.3", Commit: "abc123"})
|
||||||
|
var out bytes.Buffer
|
||||||
|
cmd.SetOut(&out)
|
||||||
|
cmd.SetArgs(args)
|
||||||
|
err := cmd.Execute()
|
||||||
|
return out.String(), err
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestVersionCommand(t *testing.T) {
|
||||||
|
out, err := runCommand(t, "version")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !strings.Contains(out, "Überbringer | Version: 1.2.3 Build: abc123") {
|
||||||
|
t.Errorf("version output = %q", out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSecretCommand(t *testing.T) {
|
||||||
|
out, err := runCommand(t, "secret")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
raw, err := base64.StdEncoding.DecodeString(strings.TrimSpace(out))
|
||||||
|
if err != nil || len(raw) != secretBytes {
|
||||||
|
t.Errorf("secret %q decodes to %d bytes, %v", out, len(raw), err)
|
||||||
|
}
|
||||||
|
again, _ := runCommand(t, "secret")
|
||||||
|
if again == out {
|
||||||
|
t.Error("two secrets were identical")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTokenCommand(t *testing.T) {
|
||||||
|
secret, _ := runCommand(t, "secret")
|
||||||
|
secret = strings.TrimSpace(secret)
|
||||||
|
path := filepath.Join(t.TempDir(), "config.toml")
|
||||||
|
body := "[api]\nsecret = \"" + secret + "\"\n[printer]\naddress = \"192.168.1.245\"\n"
|
||||||
|
if err := os.WriteFile(path, []byte(body), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
out, err := runCommand(t, "token", "-c", path, "--subject", "kitchen", "--ttl", "1h")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
claims := &jwt.RegisteredClaims{}
|
||||||
|
_, err = jwt.ParseWithClaims(strings.TrimSpace(out), claims, func(*jwt.Token) (any, error) {
|
||||||
|
return []byte(secret), nil
|
||||||
|
}, jwt.WithValidMethods([]string{"HS256"}))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("token does not verify: %v", err)
|
||||||
|
}
|
||||||
|
if claims.Subject != "kitchen" || claims.ExpiresAt == nil {
|
||||||
|
t.Errorf("claims = %+v", claims)
|
||||||
|
}
|
||||||
|
if left := time.Until(claims.ExpiresAt.Time); left < 59*time.Minute || left > time.Hour {
|
||||||
|
t.Errorf("expires in %v, want about 1h", left)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTokenCommandNoExpiryByDefault(t *testing.T) {
|
||||||
|
token, err := signToken([]byte("0123456789abcdef0123456789abcdef"), "x", 0, time.Now())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
claims := &jwt.RegisteredClaims{}
|
||||||
|
if _, _, err := jwt.NewParser().ParseUnverified(token, claims); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if claims.ExpiresAt != nil {
|
||||||
|
t.Errorf("ExpiresAt = %v, want none", claims.ExpiresAt)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestServeRejectsBadConfig(t *testing.T) {
|
||||||
|
_, err := runCommand(t, "-c", filepath.Join(t.TempDir(), "missing.toml"))
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("serve with a missing config must fail")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNewRequestID(t *testing.T) {
|
||||||
|
id := newRequestID()
|
||||||
|
if !strings.HasPrefix(id, "req_") || len(id) != len("req_")+26 {
|
||||||
|
t.Errorf("request ID %q is not a req_ TypeID", id)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,177 @@
|
|||||||
|
package uberbringer
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"log/slog"
|
||||||
|
"net"
|
||||||
|
"os"
|
||||||
|
"strconv"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/getsentry/sentry-go"
|
||||||
|
"go.jetify.com/typeid"
|
||||||
|
"golang.org/x/sync/errgroup"
|
||||||
|
|
||||||
|
"git.anomalous.dev/57_Wolve/uberbringer/internal/app/uberbringer/server"
|
||||||
|
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/config"
|
||||||
|
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/escpos"
|
||||||
|
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/printer"
|
||||||
|
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/printqueue"
|
||||||
|
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/receipt"
|
||||||
|
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/safehttp"
|
||||||
|
)
|
||||||
|
|
||||||
|
// sentryFlushTimeout bounds how long shutdown waits for queued error reports.
|
||||||
|
const sentryFlushTimeout = 2 * time.Second
|
||||||
|
|
||||||
|
// serve loads the config, wires every component and runs until ctx is
|
||||||
|
// cancelled.
|
||||||
|
func serve(ctx context.Context, configPath string, build BuildInfo, out io.Writer) error {
|
||||||
|
cfg, err := config.Load(configPath)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
logger := newLogger(cfg.Log, os.Stderr)
|
||||||
|
printBanner(out, build)
|
||||||
|
|
||||||
|
profile, err := escpos.LookupProfile(cfg.Printer.Model)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("config printer.model: %w", err)
|
||||||
|
}
|
||||||
|
if cfg.Printer.PaperWidth > 0 {
|
||||||
|
profile.DotsPerLine = cfg.Printer.PaperWidth
|
||||||
|
}
|
||||||
|
codePage, err := escpos.ParseCodePage(cfg.Printer.CodePage)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("config printer.codepage: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
flushSentry, err := initSentry(cfg.Sentry, build, logger)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer flushSentry()
|
||||||
|
|
||||||
|
fetcher := safehttp.New(safehttp.Options{
|
||||||
|
Timeout: cfg.Images.Timeout,
|
||||||
|
MaxBytes: cfg.Images.MaxBytes,
|
||||||
|
AllowPrivate: cfg.Images.AllowPrivateNetworks,
|
||||||
|
AllowedHosts: cfg.Images.AllowedHosts,
|
||||||
|
})
|
||||||
|
renderer := receipt.NewRenderer(receipt.Options{
|
||||||
|
Profile: profile,
|
||||||
|
CodePage: codePage,
|
||||||
|
Columns: cfg.Printer.Columns,
|
||||||
|
MaxPixels: cfg.Images.MaxPixels,
|
||||||
|
MaxHeight: cfg.Images.MaxHeight,
|
||||||
|
}, fetcher)
|
||||||
|
printerClient := printer.NewClient(
|
||||||
|
net.JoinHostPort(cfg.Printer.Address, strconv.Itoa(cfg.Printer.Port)),
|
||||||
|
cfg.Printer.DialTimeout, cfg.Printer.WriteTimeout)
|
||||||
|
queue := printqueue.New(renderer, printerClient, logger, printqueue.Options{
|
||||||
|
Size: cfg.Queue.Size,
|
||||||
|
History: cfg.Queue.History,
|
||||||
|
Retries: cfg.Printer.Retries,
|
||||||
|
RetryDelay: cfg.Printer.RetryDelay,
|
||||||
|
OnFailure: reportJobFailure,
|
||||||
|
})
|
||||||
|
srv := server.New(server.Config{
|
||||||
|
Info: server.Info{
|
||||||
|
Project: Project,
|
||||||
|
Description: Description,
|
||||||
|
Authors: Authors,
|
||||||
|
Version: build.Version,
|
||||||
|
Build: build.Commit,
|
||||||
|
},
|
||||||
|
Secret: []byte(cfg.API.Secret),
|
||||||
|
RateLimit: cfg.WebServer.RateLimit,
|
||||||
|
RateWindow: cfg.WebServer.RateWindow,
|
||||||
|
TrustedProxies: cfg.WebServer.TrustedProxies,
|
||||||
|
ProxyHeader: cfg.WebServer.ProxyHeader,
|
||||||
|
BodyLimit: cfg.WebServer.BodyLimit,
|
||||||
|
ReadTimeout: cfg.WebServer.ReadTimeout,
|
||||||
|
WriteTimeout: cfg.WebServer.WriteTimeout,
|
||||||
|
IdleTimeout: cfg.WebServer.IdleTimeout,
|
||||||
|
RequestID: newRequestID,
|
||||||
|
}, queue, printerClient, logger)
|
||||||
|
|
||||||
|
addr := net.JoinHostPort(cfg.WebServer.BindIP, strconv.Itoa(cfg.WebServer.Port))
|
||||||
|
var lc net.ListenConfig
|
||||||
|
ln, err := lc.Listen(ctx, "tcp", addr)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("listening on %s: %w", addr, err)
|
||||||
|
}
|
||||||
|
logger.Info("listening",
|
||||||
|
"addr", ln.Addr().String(),
|
||||||
|
"printer", printerClient.Addr(),
|
||||||
|
"model", profile.Name,
|
||||||
|
"codepage", codePage.String(),
|
||||||
|
"paper_dots", profile.DotsPerLine)
|
||||||
|
|
||||||
|
group, groupCtx := errgroup.WithContext(ctx)
|
||||||
|
group.Go(func() error { return queue.Run(groupCtx) })
|
||||||
|
group.Go(func() error { return srv.Serve(groupCtx, ln) })
|
||||||
|
err = group.Wait()
|
||||||
|
logger.Info("shutdown complete")
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// newLogger builds the structured logger described by cfg.
|
||||||
|
func newLogger(cfg config.LogConfig, w io.Writer) *slog.Logger {
|
||||||
|
var level slog.Level
|
||||||
|
// config.Validate has already checked the level name.
|
||||||
|
_ = level.UnmarshalText([]byte(cfg.Level))
|
||||||
|
options := &slog.HandlerOptions{Level: level}
|
||||||
|
if cfg.Format == config.LogFormatJSON {
|
||||||
|
return slog.New(slog.NewJSONHandler(w, options))
|
||||||
|
}
|
||||||
|
return slog.New(slog.NewTextHandler(w, options))
|
||||||
|
}
|
||||||
|
|
||||||
|
// initSentry enables error reporting when a DSN is configured and returns a
|
||||||
|
// func that flushes pending events.
|
||||||
|
func initSentry(cfg config.SentryConfig, build BuildInfo, logger *slog.Logger) (func(), error) {
|
||||||
|
dsn := cfg.DSN
|
||||||
|
if dsn == "" {
|
||||||
|
dsn = build.SentryDSN
|
||||||
|
}
|
||||||
|
if dsn == "" {
|
||||||
|
logger.Info("error reporting disabled: no Sentry DSN configured")
|
||||||
|
return func() {}, nil
|
||||||
|
}
|
||||||
|
// Leaving DataCollection unset keeps the SDK's no-PII defaults: no user
|
||||||
|
// data, cookies or sensitive headers. The HTTP middleware also never
|
||||||
|
// attaches request bodies, which hold the text being printed.
|
||||||
|
err := sentry.Init(sentry.ClientOptions{
|
||||||
|
Dsn: dsn,
|
||||||
|
Environment: cfg.Environment,
|
||||||
|
Release: "uberbringer@" + build.Version,
|
||||||
|
Debug: cfg.Debug,
|
||||||
|
AttachStacktrace: true,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("initializing Sentry: %w", err)
|
||||||
|
}
|
||||||
|
logger.Info("error reporting enabled", "environment", cfg.Environment)
|
||||||
|
return func() { sentry.Flush(sentryFlushTimeout) }, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// reportJobFailure sends a failed print job to Sentry.
|
||||||
|
func reportJobFailure(id printqueue.JobID, err error) {
|
||||||
|
hub := sentry.CurrentHub().Clone()
|
||||||
|
hub.Scope().SetTag("job_id", id.String())
|
||||||
|
hub.CaptureException(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// newRequestID returns a "req_" TypeID.
|
||||||
|
func newRequestID() string {
|
||||||
|
id, err := typeid.WithPrefix("req")
|
||||||
|
if err != nil {
|
||||||
|
// Only possible if the system random source fails; a timestamp still
|
||||||
|
// lets log lines for one request be correlated.
|
||||||
|
return "req_" + strconv.FormatInt(time.Now().UnixNano(), 36)
|
||||||
|
}
|
||||||
|
return id.String()
|
||||||
|
}
|
||||||
@@ -0,0 +1,167 @@
|
|||||||
|
package uberbringer
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// fakePrinter records everything sent to it.
|
||||||
|
type fakePrinter struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
data bytes.Buffer
|
||||||
|
addr *net.TCPAddr
|
||||||
|
}
|
||||||
|
|
||||||
|
func startFakePrinter(t *testing.T) *fakePrinter {
|
||||||
|
t.Helper()
|
||||||
|
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { _ = ln.Close() })
|
||||||
|
p := &fakePrinter{addr: ln.Addr().(*net.TCPAddr)}
|
||||||
|
go func() {
|
||||||
|
for {
|
||||||
|
conn, err := ln.Accept()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
go func() {
|
||||||
|
defer conn.Close()
|
||||||
|
data, _ := io.ReadAll(conn)
|
||||||
|
p.mu.Lock()
|
||||||
|
defer p.mu.Unlock()
|
||||||
|
p.data.Write(data)
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
return p
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *fakePrinter) received() []byte {
|
||||||
|
p.mu.Lock()
|
||||||
|
defer p.mu.Unlock()
|
||||||
|
return bytes.Clone(p.data.Bytes())
|
||||||
|
}
|
||||||
|
|
||||||
|
func freePort(t *testing.T) int {
|
||||||
|
t.Helper()
|
||||||
|
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer ln.Close()
|
||||||
|
return ln.Addr().(*net.TCPAddr).Port
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestServeEndToEnd runs the real wiring: config, queue, renderer, printer
|
||||||
|
// client and HTTP server, then checks a graceful shutdown.
|
||||||
|
func TestServeEndToEnd(t *testing.T) {
|
||||||
|
printer := startFakePrinter(t)
|
||||||
|
port := freePort(t)
|
||||||
|
const secret = "end-to-end-secret-end-to-end-secret!"
|
||||||
|
path := filepath.Join(t.TempDir(), "config.toml")
|
||||||
|
cfg := fmt.Sprintf(`
|
||||||
|
[webserver]
|
||||||
|
port = %d
|
||||||
|
[api]
|
||||||
|
secret = %q
|
||||||
|
[printer]
|
||||||
|
address = "127.0.0.1"
|
||||||
|
port = %d
|
||||||
|
[log]
|
||||||
|
level = "error"
|
||||||
|
`, port, secret, printer.addr.Port)
|
||||||
|
if err := os.WriteFile(path, []byte(cfg), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
defer cancel()
|
||||||
|
served := make(chan error, 1)
|
||||||
|
go func() { served <- serve(ctx, path, BuildInfo{Version: "test"}, io.Discard) }()
|
||||||
|
|
||||||
|
base := fmt.Sprintf("http://127.0.0.1:%d", port)
|
||||||
|
waitFor(t, func() bool {
|
||||||
|
resp, err := http.Get(base + "/")
|
||||||
|
if err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
resp.Body.Close()
|
||||||
|
return resp.StatusCode == http.StatusOK
|
||||||
|
})
|
||||||
|
|
||||||
|
token, err := signToken([]byte(secret), "test", 0, time.Now())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
req, _ := http.NewRequest(http.MethodPost, base+"/api/v1/print",
|
||||||
|
strings.NewReader(`{"elements":[{"type":"text","text":"Grüße aus dem Test"}]}`))
|
||||||
|
req.Header.Set("Authorization", "Bearer "+token)
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
resp, err := http.DefaultClient.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var queued struct{ ID, Status string }
|
||||||
|
if err := json.NewDecoder(resp.Body).Decode(&queued); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
resp.Body.Close()
|
||||||
|
if resp.StatusCode != http.StatusAccepted || !strings.HasPrefix(queued.ID, "job_") {
|
||||||
|
t.Fatalf("POST = %d %+v", resp.StatusCode, queued)
|
||||||
|
}
|
||||||
|
|
||||||
|
waitFor(t, func() bool {
|
||||||
|
req, _ := http.NewRequest(http.MethodGet, base+"/api/v1/jobs/"+queued.ID, nil)
|
||||||
|
req.Header.Set("Authorization", "Bearer "+token)
|
||||||
|
resp, err := http.DefaultClient.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
var st struct{ Status string }
|
||||||
|
_ = json.NewDecoder(resp.Body).Decode(&st)
|
||||||
|
return st.Status == "done"
|
||||||
|
})
|
||||||
|
waitFor(t, func() bool {
|
||||||
|
// "Grüße" in CP437: ü is 0x81, ß is 0xE1.
|
||||||
|
return bytes.Contains(printer.received(), []byte("Gr\x81\xE1e aus dem Test"))
|
||||||
|
})
|
||||||
|
|
||||||
|
cancel()
|
||||||
|
select {
|
||||||
|
case err := <-served:
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("serve returned %v after shutdown", err)
|
||||||
|
}
|
||||||
|
case <-time.After(15 * time.Second):
|
||||||
|
t.Fatal("serve did not shut down")
|
||||||
|
}
|
||||||
|
if _, err := http.Get(base + "/"); err == nil {
|
||||||
|
t.Error("server still accepting connections after shutdown")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func waitFor(t *testing.T, cond func() bool) {
|
||||||
|
t.Helper()
|
||||||
|
deadline := time.Now().Add(10 * time.Second)
|
||||||
|
for time.Now().Before(deadline) {
|
||||||
|
if cond() {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
time.Sleep(20 * time.Millisecond)
|
||||||
|
}
|
||||||
|
t.Fatal("condition not met within 10s")
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/gofiber/fiber/v3"
|
||||||
|
"github.com/golang-jwt/jwt/v5"
|
||||||
|
)
|
||||||
|
|
||||||
|
// requireBearerToken rejects requests without a valid HS256 bearer token.
|
||||||
|
// Tokens are only read from the Authorization header: query-string tokens
|
||||||
|
// end up in proxy and access logs.
|
||||||
|
func requireBearerToken(secret []byte) fiber.Handler {
|
||||||
|
parser := jwt.NewParser(jwt.WithValidMethods([]string{jwt.SigningMethodHS256.Alg()}))
|
||||||
|
keyFunc := func(*jwt.Token) (any, error) { return secret, nil }
|
||||||
|
|
||||||
|
return func(c fiber.Ctx) error {
|
||||||
|
token, ok := bearerToken(c.Get(fiber.HeaderAuthorization))
|
||||||
|
if !ok {
|
||||||
|
c.Set(fiber.HeaderWWWAuthenticate, `Bearer realm="uberbringer"`)
|
||||||
|
return fiber.NewError(fiber.StatusUnauthorized, "missing bearer token")
|
||||||
|
}
|
||||||
|
if _, err := parser.Parse(token, keyFunc); err != nil {
|
||||||
|
c.Set(fiber.HeaderWWWAuthenticate, `Bearer realm="uberbringer", error="invalid_token"`)
|
||||||
|
return fiber.NewError(fiber.StatusUnauthorized, "invalid or expired token")
|
||||||
|
}
|
||||||
|
return c.Next()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// bearerToken extracts the token from an Authorization header value. The
|
||||||
|
// scheme is case-insensitive (RFC 7235).
|
||||||
|
func bearerToken(header string) (string, bool) {
|
||||||
|
const scheme = "bearer "
|
||||||
|
if len(header) <= len(scheme) || !strings.EqualFold(header[:len(scheme)], scheme) {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
token := strings.TrimSpace(header[len(scheme):])
|
||||||
|
return token, token != ""
|
||||||
|
}
|
||||||
@@ -0,0 +1,204 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/gofiber/fiber/v3"
|
||||||
|
|
||||||
|
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/printer"
|
||||||
|
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/printqueue"
|
||||||
|
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/receipt"
|
||||||
|
)
|
||||||
|
|
||||||
|
// healthTimeout bounds the printer status check behind /healthz.
|
||||||
|
const healthTimeout = 3 * time.Second
|
||||||
|
|
||||||
|
// apiError is an error with an HTTP status and optional details.
|
||||||
|
type apiError struct {
|
||||||
|
status int
|
||||||
|
message string
|
||||||
|
details []string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *apiError) Error() string { return e.message }
|
||||||
|
|
||||||
|
// errorResponse is the JSON body of every error.
|
||||||
|
type errorResponse struct {
|
||||||
|
Error string `json:"error"`
|
||||||
|
Details []string `json:"details,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// handleError turns errors into JSON responses. Server errors are logged and
|
||||||
|
// reported to Sentry here, once, at the HTTP boundary.
|
||||||
|
func (s *Server) handleError(c fiber.Ctx, err error) error {
|
||||||
|
resp := errorResponse{Error: "internal server error"}
|
||||||
|
status := fiber.StatusInternalServerError
|
||||||
|
|
||||||
|
var (
|
||||||
|
apiErr *apiError
|
||||||
|
fiberErr *fiber.Error
|
||||||
|
)
|
||||||
|
switch {
|
||||||
|
case errors.As(err, &apiErr):
|
||||||
|
status, resp.Error, resp.Details = apiErr.status, apiErr.message, apiErr.details
|
||||||
|
case errors.As(err, &fiberErr):
|
||||||
|
status, resp.Error = fiberErr.Code, fiberErr.Message
|
||||||
|
}
|
||||||
|
if status >= fiber.StatusInternalServerError {
|
||||||
|
s.logger.Error("request failed", "path", c.Path(), "err", err)
|
||||||
|
hubFrom(c).CaptureException(err)
|
||||||
|
}
|
||||||
|
return c.Status(status).JSON(resp)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) handleIndex(c fiber.Ctx) error {
|
||||||
|
info := s.config.Info
|
||||||
|
return c.JSON(fiber.Map{
|
||||||
|
"Project": info.Project,
|
||||||
|
"Description": info.Description,
|
||||||
|
"Authors": info.Authors,
|
||||||
|
"Version": info.Version,
|
||||||
|
"Build": info.Build,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func handleRobots(c fiber.Ctx) error {
|
||||||
|
return c.SendString("User-agent: *\nDisallow:\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
// handlePrint validates and queues a job.
|
||||||
|
func (s *Server) handlePrint(c fiber.Ctx) error {
|
||||||
|
job, err := decodeJob(c.Body())
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := job.Validate(); err != nil {
|
||||||
|
var ve *receipt.ValidationError
|
||||||
|
if errors.As(err, &ve) {
|
||||||
|
return &apiError{status: fiber.StatusBadRequest, message: "invalid job", details: ve.Problems}
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
status, err := s.jobs.Submit(job)
|
||||||
|
switch {
|
||||||
|
case errors.Is(err, printqueue.ErrQueueFull):
|
||||||
|
c.Set(fiber.HeaderRetryAfter, "10")
|
||||||
|
return fiber.NewError(fiber.StatusServiceUnavailable, "print queue is full, try again shortly")
|
||||||
|
case errors.Is(err, printqueue.ErrClosed):
|
||||||
|
return fiber.NewError(fiber.StatusServiceUnavailable, "server is shutting down")
|
||||||
|
case err != nil:
|
||||||
|
return fmt.Errorf("submitting job: %w", err)
|
||||||
|
}
|
||||||
|
c.Location("/api/v1/jobs/" + status.ID.String())
|
||||||
|
return c.Status(fiber.StatusAccepted).JSON(status)
|
||||||
|
}
|
||||||
|
|
||||||
|
// decodeJob strictly decodes a job body. Unknown fields are rejected so typos
|
||||||
|
// and the pre-refactor {"data": [...]} format fail loudly.
|
||||||
|
func decodeJob(body []byte) (receipt.Job, error) {
|
||||||
|
var job receipt.Job
|
||||||
|
dec := json.NewDecoder(bytes.NewReader(body))
|
||||||
|
dec.DisallowUnknownFields()
|
||||||
|
if err := dec.Decode(&job); err != nil {
|
||||||
|
msg := "request body is not a valid job: " + err.Error()
|
||||||
|
if strings.Contains(err.Error(), `unknown field "data"`) {
|
||||||
|
msg = `the {"data": [...]} format was replaced by {"elements": [...]}; see the README for the element format`
|
||||||
|
}
|
||||||
|
return job, &apiError{status: fiber.StatusBadRequest, message: msg}
|
||||||
|
}
|
||||||
|
if _, err := dec.Token(); !errors.Is(err, io.EOF) {
|
||||||
|
return job, &apiError{status: fiber.StatusBadRequest, message: "request body has trailing data after the job"}
|
||||||
|
}
|
||||||
|
return job, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// handleJob returns the status of one job.
|
||||||
|
func (s *Server) handleJob(c fiber.Ctx) error {
|
||||||
|
// Clone: fasthttp reuses the buffer behind route params.
|
||||||
|
id, err := printqueue.ParseJobID(strings.Clone(c.Params("id")))
|
||||||
|
if err != nil {
|
||||||
|
return fiber.NewError(fiber.StatusNotFound, "job not found")
|
||||||
|
}
|
||||||
|
status, err := s.jobs.Status(id)
|
||||||
|
if errors.Is(err, printqueue.ErrNotFound) {
|
||||||
|
return fiber.NewError(fiber.StatusNotFound, "job not found")
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return c.JSON(status)
|
||||||
|
}
|
||||||
|
|
||||||
|
// printerHealth is the printer part of the /healthz response.
|
||||||
|
type printerHealth struct {
|
||||||
|
Reachable bool `json:"reachable"`
|
||||||
|
Status string `json:"status"`
|
||||||
|
Online *bool `json:"online,omitempty"`
|
||||||
|
CoverOpen *bool `json:"cover_open,omitempty"`
|
||||||
|
Paper string `json:"paper,omitempty"`
|
||||||
|
Error string `json:"error,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type healthResponse struct {
|
||||||
|
Status string `json:"status"`
|
||||||
|
Printer printerHealth `json:"printer"`
|
||||||
|
Queue struct {
|
||||||
|
Pending int `json:"pending"`
|
||||||
|
} `json:"queue"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// handleHealth reports whether the printer is reachable and ready. It
|
||||||
|
// answers 503 when it is not, so load balancers and monitors can alert.
|
||||||
|
func (s *Server) handleHealth(c fiber.Ctx) error {
|
||||||
|
ctx, cancel := context.WithTimeout(c.Context(), healthTimeout)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
var resp healthResponse
|
||||||
|
resp.Queue.Pending = s.jobs.Pending()
|
||||||
|
httpStatus := fiber.StatusOK
|
||||||
|
|
||||||
|
st, err := s.printer.Status(ctx)
|
||||||
|
switch {
|
||||||
|
case errors.Is(err, printer.ErrStatusUnsupported):
|
||||||
|
resp.Status = "ok"
|
||||||
|
resp.Printer = printerHealth{Reachable: true, Status: "unknown"}
|
||||||
|
case err != nil:
|
||||||
|
s.logger.Warn("printer health check failed", "err", err)
|
||||||
|
resp.Status = "unavailable"
|
||||||
|
resp.Printer = printerHealth{Reachable: false, Status: "unreachable"}
|
||||||
|
httpStatus = fiber.StatusServiceUnavailable
|
||||||
|
default:
|
||||||
|
paper := "ok"
|
||||||
|
switch {
|
||||||
|
case st.PaperOut:
|
||||||
|
paper = "out"
|
||||||
|
case st.PaperNearEnd:
|
||||||
|
paper = "near_end"
|
||||||
|
}
|
||||||
|
resp.Printer = printerHealth{
|
||||||
|
Reachable: true,
|
||||||
|
Status: "ready",
|
||||||
|
Online: &st.Online,
|
||||||
|
CoverOpen: &st.CoverOpen,
|
||||||
|
Paper: paper,
|
||||||
|
}
|
||||||
|
resp.Status = "ok"
|
||||||
|
if !st.Ready() {
|
||||||
|
resp.Status = "degraded"
|
||||||
|
resp.Printer.Status = "not_ready"
|
||||||
|
if st.CutterError || st.Unrecoverable || st.AutoRecoverable {
|
||||||
|
resp.Printer.Error = "printer reports an error"
|
||||||
|
}
|
||||||
|
httpStatus = fiber.StatusServiceUnavailable
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return c.Status(httpStatus).JSON(resp)
|
||||||
|
}
|
||||||
@@ -0,0 +1,194 @@
|
|||||||
|
// Package server exposes the Überbringer HTTP API on Fiber.
|
||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"log/slog"
|
||||||
|
"net"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/getsentry/sentry-go"
|
||||||
|
"github.com/gofiber/fiber/v3"
|
||||||
|
"github.com/gofiber/fiber/v3/middleware/compress"
|
||||||
|
"github.com/gofiber/fiber/v3/middleware/limiter"
|
||||||
|
recoverer "github.com/gofiber/fiber/v3/middleware/recover" // avoids shadowing the recover builtin
|
||||||
|
"github.com/gofiber/fiber/v3/middleware/requestid"
|
||||||
|
|
||||||
|
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/escpos"
|
||||||
|
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/printqueue"
|
||||||
|
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/receipt"
|
||||||
|
)
|
||||||
|
|
||||||
|
// shutdownTimeout bounds how long in-flight requests may take to finish.
|
||||||
|
const shutdownTimeout = 10 * time.Second
|
||||||
|
|
||||||
|
// Jobs is the print queue as seen by the HTTP handlers.
|
||||||
|
type Jobs interface {
|
||||||
|
Submit(job receipt.Job) (printqueue.Status, error)
|
||||||
|
Status(id printqueue.JobID) (printqueue.Status, error)
|
||||||
|
Pending() int
|
||||||
|
}
|
||||||
|
|
||||||
|
// Printer reports the printer's real-time status.
|
||||||
|
type Printer interface {
|
||||||
|
Status(ctx context.Context) (escpos.Status, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Info describes the running build for the index route.
|
||||||
|
type Info struct {
|
||||||
|
Project string
|
||||||
|
Description string
|
||||||
|
Authors string
|
||||||
|
Version string
|
||||||
|
Build string
|
||||||
|
}
|
||||||
|
|
||||||
|
// Config configures the HTTP server.
|
||||||
|
type Config struct {
|
||||||
|
Info Info
|
||||||
|
|
||||||
|
// Secret is the HS256 key bearer tokens must be signed with.
|
||||||
|
Secret []byte
|
||||||
|
|
||||||
|
// RateLimit requests per RateWindow are allowed per client IP on /api.
|
||||||
|
RateLimit int
|
||||||
|
RateWindow time.Duration
|
||||||
|
|
||||||
|
// TrustedProxies may set ProxyHeader to the real client IP.
|
||||||
|
TrustedProxies []string
|
||||||
|
ProxyHeader string
|
||||||
|
|
||||||
|
BodyLimit int
|
||||||
|
ReadTimeout time.Duration
|
||||||
|
WriteTimeout time.Duration
|
||||||
|
IdleTimeout time.Duration
|
||||||
|
|
||||||
|
// RequestID generates request IDs.
|
||||||
|
RequestID func() string
|
||||||
|
}
|
||||||
|
|
||||||
|
// Server is the HTTP API.
|
||||||
|
type Server struct {
|
||||||
|
app *fiber.App
|
||||||
|
config Config
|
||||||
|
jobs Jobs
|
||||||
|
printer Printer
|
||||||
|
logger *slog.Logger
|
||||||
|
}
|
||||||
|
|
||||||
|
// New builds the server and its routes.
|
||||||
|
func New(config Config, jobs Jobs, printer Printer, logger *slog.Logger) *Server {
|
||||||
|
switch {
|
||||||
|
case jobs == nil || printer == nil || logger == nil:
|
||||||
|
panic("server.New: jobs, printer and logger must not be nil")
|
||||||
|
case len(config.Secret) == 0:
|
||||||
|
panic("server.New: secret must not be empty")
|
||||||
|
case config.RequestID == nil:
|
||||||
|
panic("server.New: RequestID must not be nil")
|
||||||
|
}
|
||||||
|
s := &Server{config: config, jobs: jobs, printer: printer, logger: logger}
|
||||||
|
|
||||||
|
s.app = fiber.New(fiber.Config{
|
||||||
|
AppName: config.Info.Project,
|
||||||
|
BodyLimit: config.BodyLimit,
|
||||||
|
ReadTimeout: config.ReadTimeout,
|
||||||
|
WriteTimeout: config.WriteTimeout,
|
||||||
|
IdleTimeout: config.IdleTimeout,
|
||||||
|
ErrorHandler: s.handleError,
|
||||||
|
TrustProxy: len(config.TrustedProxies) > 0,
|
||||||
|
ProxyHeader: config.ProxyHeader,
|
||||||
|
EnableIPValidation: true,
|
||||||
|
TrustProxyConfig: fiber.TrustProxyConfig{Proxies: config.TrustedProxies},
|
||||||
|
})
|
||||||
|
|
||||||
|
s.app.Use(recoverer.New())
|
||||||
|
s.app.Use(sentryMiddleware)
|
||||||
|
s.app.Use(requestid.New(requestid.Config{Generator: config.RequestID}))
|
||||||
|
s.app.Use(s.logRequests)
|
||||||
|
s.app.Use(compress.New(compress.Config{Level: compress.LevelBestSpeed}))
|
||||||
|
|
||||||
|
s.app.Get("/", s.handleIndex)
|
||||||
|
s.app.Get("/robots.txt", handleRobots)
|
||||||
|
s.app.Get("/healthz", s.handleHealth)
|
||||||
|
|
||||||
|
api := s.app.Group("/api/v1",
|
||||||
|
limiter.New(limiter.Config{
|
||||||
|
Max: config.RateLimit,
|
||||||
|
Expiration: config.RateWindow,
|
||||||
|
KeyGenerator: func(c fiber.Ctx) string { return c.IP() },
|
||||||
|
LimitReached: func(fiber.Ctx) error { return fiber.ErrTooManyRequests },
|
||||||
|
}),
|
||||||
|
requireBearerToken(config.Secret),
|
||||||
|
)
|
||||||
|
api.Post("/print", s.handlePrint)
|
||||||
|
api.Get("/jobs/:id", s.handleJob)
|
||||||
|
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
// Serve accepts connections on ln until ctx is cancelled, then shuts down
|
||||||
|
// gracefully.
|
||||||
|
func (s *Server) Serve(ctx context.Context, ln net.Listener) error {
|
||||||
|
err := s.app.Listener(ln, fiber.ListenConfig{
|
||||||
|
GracefulContext: ctx,
|
||||||
|
ShutdownTimeout: shutdownTimeout,
|
||||||
|
DisableStartupMessage: true,
|
||||||
|
})
|
||||||
|
if err != nil && !errors.Is(err, net.ErrClosed) {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// logRequests logs every request once, after the error handler has set the
|
||||||
|
// final status. Only the path is logged, never the query string.
|
||||||
|
func (s *Server) logRequests(c fiber.Ctx) error {
|
||||||
|
start := time.Now()
|
||||||
|
if err := c.Next(); err != nil {
|
||||||
|
if handlerErr := s.handleError(c, err); handlerErr != nil {
|
||||||
|
return handlerErr
|
||||||
|
}
|
||||||
|
}
|
||||||
|
status := c.Response().StatusCode()
|
||||||
|
level := slog.LevelInfo
|
||||||
|
if status >= fiber.StatusInternalServerError {
|
||||||
|
level = slog.LevelError
|
||||||
|
}
|
||||||
|
s.logger.LogAttrs(c.Context(), level, "request",
|
||||||
|
slog.String("method", c.Method()),
|
||||||
|
slog.String("path", c.Path()),
|
||||||
|
slog.Int("status", status),
|
||||||
|
slog.Duration("latency", time.Since(start)),
|
||||||
|
slog.String("ip", c.IP()),
|
||||||
|
slog.String("request_id", requestid.FromContext(c)),
|
||||||
|
)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// sentryHubKey stores the per-request Sentry hub in fiber Locals.
|
||||||
|
type sentryHubKey struct{}
|
||||||
|
|
||||||
|
// sentryMiddleware reports panics to Sentry with a per-request hub, then
|
||||||
|
// re-panics so the recover middleware can turn them into a 500. Request
|
||||||
|
// bodies are deliberately not attached: they hold the text being printed.
|
||||||
|
func sentryMiddleware(c fiber.Ctx) error {
|
||||||
|
hub := sentry.CurrentHub().Clone()
|
||||||
|
hub.Scope().SetTag("method", c.Method())
|
||||||
|
hub.Scope().SetTag("path", c.Path())
|
||||||
|
c.Locals(sentryHubKey{}, hub)
|
||||||
|
defer func() {
|
||||||
|
if r := recover(); r != nil {
|
||||||
|
hub.Recover(r)
|
||||||
|
panic(r)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
return c.Next()
|
||||||
|
}
|
||||||
|
|
||||||
|
func hubFrom(c fiber.Ctx) *sentry.Hub {
|
||||||
|
if hub, ok := c.Locals(sentryHubKey{}).(*sentry.Hub); ok {
|
||||||
|
return hub
|
||||||
|
}
|
||||||
|
return sentry.CurrentHub()
|
||||||
|
}
|
||||||
@@ -0,0 +1,377 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"log/slog"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/golang-jwt/jwt/v5"
|
||||||
|
|
||||||
|
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/escpos"
|
||||||
|
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/printer"
|
||||||
|
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/printqueue"
|
||||||
|
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/receipt"
|
||||||
|
)
|
||||||
|
|
||||||
|
var testSecret = []byte("0123456789abcdef0123456789abcdef")
|
||||||
|
|
||||||
|
type fakeJobs struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
submitted []receipt.Job
|
||||||
|
submitErr error
|
||||||
|
statuses map[printqueue.JobID]printqueue.Status
|
||||||
|
nextID printqueue.JobID
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fakeJobs) Submit(job receipt.Job) (printqueue.Status, error) {
|
||||||
|
f.mu.Lock()
|
||||||
|
defer f.mu.Unlock()
|
||||||
|
if f.submitErr != nil {
|
||||||
|
return printqueue.Status{}, f.submitErr
|
||||||
|
}
|
||||||
|
f.submitted = append(f.submitted, job)
|
||||||
|
st := printqueue.Status{ID: f.nextID, State: printqueue.StateQueued, CreatedAt: time.Now()}
|
||||||
|
f.statuses[f.nextID] = st
|
||||||
|
return st, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fakeJobs) Status(id printqueue.JobID) (printqueue.Status, error) {
|
||||||
|
f.mu.Lock()
|
||||||
|
defer f.mu.Unlock()
|
||||||
|
st, ok := f.statuses[id]
|
||||||
|
if !ok {
|
||||||
|
return printqueue.Status{}, printqueue.ErrNotFound
|
||||||
|
}
|
||||||
|
return st, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fakeJobs) Pending() int { return 0 }
|
||||||
|
|
||||||
|
type fakePrinter struct {
|
||||||
|
status escpos.Status
|
||||||
|
err error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f fakePrinter) Status(context.Context) (escpos.Status, error) { return f.status, f.err }
|
||||||
|
|
||||||
|
func newJobID(t *testing.T) printqueue.JobID {
|
||||||
|
t.Helper()
|
||||||
|
id, err := printqueue.ParseJobID("job_01h455vb4pex5vsknk084sn02q")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return id
|
||||||
|
}
|
||||||
|
|
||||||
|
func newTestServer(t *testing.T, jobs *fakeJobs, p Printer) *Server {
|
||||||
|
t.Helper()
|
||||||
|
if jobs.statuses == nil {
|
||||||
|
jobs.statuses = map[printqueue.JobID]printqueue.Status{}
|
||||||
|
}
|
||||||
|
return New(Config{
|
||||||
|
Info: Info{Project: "Überbringer", Version: "test"},
|
||||||
|
Secret: testSecret,
|
||||||
|
RateLimit: 1000,
|
||||||
|
RateWindow: time.Minute,
|
||||||
|
TrustedProxies: []string{"127.0.0.1"},
|
||||||
|
ProxyHeader: "X-Real-IP",
|
||||||
|
BodyLimit: 1 << 20,
|
||||||
|
ReadTimeout: time.Second,
|
||||||
|
WriteTimeout: time.Second,
|
||||||
|
IdleTimeout: time.Second,
|
||||||
|
RequestID: func() string { return "req_test" },
|
||||||
|
}, jobs, p, slog.New(slog.NewTextHandler(io.Discard, nil)))
|
||||||
|
}
|
||||||
|
|
||||||
|
func token(t *testing.T, secret []byte, method jwt.SigningMethod, claims jwt.Claims) string {
|
||||||
|
t.Helper()
|
||||||
|
signed, err := jwt.NewWithClaims(method, claims).SignedString(secret)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return signed
|
||||||
|
}
|
||||||
|
|
||||||
|
func validToken(t *testing.T) string {
|
||||||
|
return token(t, testSecret, jwt.SigningMethodHS256, jwt.MapClaims{"user_id": "uberbringer"})
|
||||||
|
}
|
||||||
|
|
||||||
|
func do(t *testing.T, s *Server, req *http.Request) (*http.Response, map[string]any) {
|
||||||
|
t.Helper()
|
||||||
|
resp, err := s.app.Test(req)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
body, _ := io.ReadAll(resp.Body)
|
||||||
|
var parsed map[string]any
|
||||||
|
_ = json.Unmarshal(body, &parsed) // some routes return plain text
|
||||||
|
return resp, parsed
|
||||||
|
}
|
||||||
|
|
||||||
|
func printRequest(t *testing.T, body, auth string) *http.Request {
|
||||||
|
t.Helper()
|
||||||
|
req := httptest.NewRequest(http.MethodPost, "/api/v1/print", strings.NewReader(body))
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
if auth != "" {
|
||||||
|
req.Header.Set("Authorization", auth)
|
||||||
|
}
|
||||||
|
return req
|
||||||
|
}
|
||||||
|
|
||||||
|
const validJob = `{"elements":[{"type":"text","text":"Hello"}]}`
|
||||||
|
|
||||||
|
func TestPrintAuth(t *testing.T) {
|
||||||
|
expired := token(t, testSecret, jwt.SigningMethodHS256, jwt.RegisteredClaims{
|
||||||
|
ExpiresAt: jwt.NewNumericDate(time.Now().Add(-time.Hour)),
|
||||||
|
})
|
||||||
|
wrongKey := token(t, []byte("another-secret-another-secret-xx"), jwt.SigningMethodHS256, jwt.MapClaims{})
|
||||||
|
hs512 := token(t, testSecret, jwt.SigningMethodHS512, jwt.MapClaims{})
|
||||||
|
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
auth string
|
||||||
|
want int
|
||||||
|
}{
|
||||||
|
{"no header", "", http.StatusUnauthorized},
|
||||||
|
{"not bearer", "Basic abc", http.StatusUnauthorized},
|
||||||
|
{"garbage token", "Bearer nope", http.StatusUnauthorized},
|
||||||
|
{"wrong key", "Bearer " + wrongKey, http.StatusUnauthorized},
|
||||||
|
{"expired", "Bearer " + expired, http.StatusUnauthorized},
|
||||||
|
{"wrong algorithm", "Bearer " + hs512, http.StatusUnauthorized},
|
||||||
|
{"legacy install.sh token", "Bearer " + validToken(t), http.StatusAccepted},
|
||||||
|
{"lowercase scheme", "bearer " + validToken(t), http.StatusAccepted},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
s := newTestServer(t, &fakeJobs{nextID: newJobID(t)}, fakePrinter{})
|
||||||
|
resp, body := do(t, s, printRequest(t, validJob, tt.auth))
|
||||||
|
if resp.StatusCode != tt.want {
|
||||||
|
t.Fatalf("status = %d, want %d (%v)", resp.StatusCode, tt.want, body)
|
||||||
|
}
|
||||||
|
if tt.want == http.StatusUnauthorized && resp.Header.Get("WWW-Authenticate") == "" {
|
||||||
|
t.Error("401 without WWW-Authenticate")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPrintQueryTokenIsNotAccepted(t *testing.T) {
|
||||||
|
s := newTestServer(t, &fakeJobs{nextID: newJobID(t)}, fakePrinter{})
|
||||||
|
req := httptest.NewRequest(http.MethodPost, "/api/v1/print?token="+validToken(t), strings.NewReader(validJob))
|
||||||
|
if resp, _ := do(t, s, req); resp.StatusCode != http.StatusUnauthorized {
|
||||||
|
t.Errorf("status = %d, want 401", resp.StatusCode)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPrintAccepted(t *testing.T) {
|
||||||
|
jobs := &fakeJobs{nextID: newJobID(t)}
|
||||||
|
s := newTestServer(t, jobs, fakePrinter{})
|
||||||
|
resp, body := do(t, s, printRequest(t, validJob, "Bearer "+validToken(t)))
|
||||||
|
if resp.StatusCode != http.StatusAccepted {
|
||||||
|
t.Fatalf("status = %d (%v)", resp.StatusCode, body)
|
||||||
|
}
|
||||||
|
if body["id"] != "job_01h455vb4pex5vsknk084sn02q" || body["status"] != "queued" {
|
||||||
|
t.Errorf("body = %v", body)
|
||||||
|
}
|
||||||
|
if loc := resp.Header.Get("Location"); loc != "/api/v1/jobs/job_01h455vb4pex5vsknk084sn02q" {
|
||||||
|
t.Errorf("Location = %q", loc)
|
||||||
|
}
|
||||||
|
if len(jobs.submitted) != 1 || jobs.submitted[0].Elements[0].Text != "Hello" {
|
||||||
|
t.Errorf("submitted %+v", jobs.submitted)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPrintBadRequests(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name, body, wantErr string
|
||||||
|
}{
|
||||||
|
{"not json", `nope`, "not a valid job"},
|
||||||
|
{"old format", `{"data":[{"type":1,"size":1,"text":"hi"}]}`, `replaced by {"elements": [...]}`},
|
||||||
|
{"unknown element field", `{"elements":[{"type":"text","colour":"red"}]}`, `unknown field "colour"`},
|
||||||
|
{"trailing data", validJob + `{}`, "trailing data"},
|
||||||
|
{"invalid element", `{"elements":[{"type":"text","size":12}]}`, "invalid job"},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
jobs := &fakeJobs{nextID: newJobID(t)}
|
||||||
|
s := newTestServer(t, jobs, fakePrinter{})
|
||||||
|
resp, body := do(t, s, printRequest(t, tt.body, "Bearer "+validToken(t)))
|
||||||
|
if resp.StatusCode != http.StatusBadRequest {
|
||||||
|
t.Fatalf("status = %d, want 400 (%v)", resp.StatusCode, body)
|
||||||
|
}
|
||||||
|
if msg, _ := body["error"].(string); !strings.Contains(msg, tt.wantErr) {
|
||||||
|
t.Errorf("error = %q, want it to contain %q", msg, tt.wantErr)
|
||||||
|
}
|
||||||
|
if len(jobs.submitted) != 0 {
|
||||||
|
t.Error("invalid job was submitted")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPrintValidationDetails(t *testing.T) {
|
||||||
|
s := newTestServer(t, &fakeJobs{nextID: newJobID(t)}, fakePrinter{})
|
||||||
|
_, body := do(t, s, printRequest(t, `{"elements":[{"type":"text","size":12},{"type":"qr"}]}`, "Bearer "+validToken(t)))
|
||||||
|
details, _ := body["details"].([]any)
|
||||||
|
if len(details) != 2 {
|
||||||
|
t.Errorf("details = %v, want 2 problems", body["details"])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPrintQueueFull(t *testing.T) {
|
||||||
|
s := newTestServer(t, &fakeJobs{submitErr: printqueue.ErrQueueFull}, fakePrinter{})
|
||||||
|
resp, _ := do(t, s, printRequest(t, validJob, "Bearer "+validToken(t)))
|
||||||
|
if resp.StatusCode != http.StatusServiceUnavailable || resp.Header.Get("Retry-After") == "" {
|
||||||
|
t.Errorf("status = %d, Retry-After = %q", resp.StatusCode, resp.Header.Get("Retry-After"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestJobStatus(t *testing.T) {
|
||||||
|
id := newJobID(t)
|
||||||
|
jobs := &fakeJobs{statuses: map[printqueue.JobID]printqueue.Status{
|
||||||
|
id: {ID: id, State: printqueue.StateDone, Attempts: 1},
|
||||||
|
}}
|
||||||
|
s := newTestServer(t, jobs, fakePrinter{})
|
||||||
|
auth := "Bearer " + validToken(t)
|
||||||
|
|
||||||
|
tests := []struct {
|
||||||
|
path string
|
||||||
|
want int
|
||||||
|
}{
|
||||||
|
{"/api/v1/jobs/" + id.String(), http.StatusOK},
|
||||||
|
{"/api/v1/jobs/job_01h455vb4pex5vsknk084sn02r", http.StatusNotFound},
|
||||||
|
{"/api/v1/jobs/not-an-id", http.StatusNotFound},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
req := httptest.NewRequest(http.MethodGet, tt.path, nil)
|
||||||
|
req.Header.Set("Authorization", auth)
|
||||||
|
resp, body := do(t, s, req)
|
||||||
|
if resp.StatusCode != tt.want {
|
||||||
|
t.Errorf("GET %s = %d, want %d", tt.path, resp.StatusCode, tt.want)
|
||||||
|
}
|
||||||
|
if tt.want == http.StatusOK && body["status"] != "done" {
|
||||||
|
t.Errorf("body = %v", body)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
req := httptest.NewRequest(http.MethodGet, "/api/v1/jobs/"+id.String(), nil)
|
||||||
|
if resp, _ := do(t, s, req); resp.StatusCode != http.StatusUnauthorized {
|
||||||
|
t.Errorf("unauthenticated status lookup = %d, want 401", resp.StatusCode)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHealth(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
printer fakePrinter
|
||||||
|
want int
|
||||||
|
wantStatus string
|
||||||
|
wantPrinter string
|
||||||
|
wantPaper string
|
||||||
|
wantReachable bool
|
||||||
|
}{
|
||||||
|
{"ready", fakePrinter{status: escpos.Status{Online: true}}, 200, "ok", "ready", "ok", true},
|
||||||
|
{"paper low still ok", fakePrinter{status: escpos.Status{Online: true, PaperNearEnd: true}}, 200, "ok", "ready", "near_end", true},
|
||||||
|
{"paper out", fakePrinter{status: escpos.Status{PaperOut: true}}, 503, "degraded", "not_ready", "out", true},
|
||||||
|
{"no status support", fakePrinter{err: printer.ErrStatusUnsupported}, 200, "ok", "unknown", "", true},
|
||||||
|
{"unreachable", fakePrinter{err: errors.New("dial tcp: timeout")}, 503, "unavailable", "unreachable", "", false},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
s := newTestServer(t, &fakeJobs{}, tt.printer)
|
||||||
|
resp, body := do(t, s, httptest.NewRequest(http.MethodGet, "/healthz", nil))
|
||||||
|
if resp.StatusCode != tt.want {
|
||||||
|
t.Fatalf("status = %d, want %d", resp.StatusCode, tt.want)
|
||||||
|
}
|
||||||
|
p, _ := body["printer"].(map[string]any)
|
||||||
|
if body["status"] != tt.wantStatus || p["status"] != tt.wantPrinter || p["reachable"] != tt.wantReachable {
|
||||||
|
t.Errorf("body = %v", body)
|
||||||
|
}
|
||||||
|
if paper, _ := p["paper"].(string); paper != tt.wantPaper {
|
||||||
|
t.Errorf("paper = %q, want %q", paper, tt.wantPaper)
|
||||||
|
}
|
||||||
|
if _, leaked := p["error"].(string); leaked && !tt.wantReachable {
|
||||||
|
t.Error("unreachable printer error text must not be exposed publicly")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestIndexAndRobotsAndNotFound(t *testing.T) {
|
||||||
|
s := newTestServer(t, &fakeJobs{}, fakePrinter{})
|
||||||
|
resp, body := do(t, s, httptest.NewRequest(http.MethodGet, "/", nil))
|
||||||
|
if resp.StatusCode != 200 || body["Project"] != "Überbringer" || body["Version"] != "test" {
|
||||||
|
t.Errorf("index = %d %v", resp.StatusCode, body)
|
||||||
|
}
|
||||||
|
if resp, _ := do(t, s, httptest.NewRequest(http.MethodGet, "/robots.txt", nil)); resp.StatusCode != 200 {
|
||||||
|
t.Errorf("robots = %d", resp.StatusCode)
|
||||||
|
}
|
||||||
|
resp, body = do(t, s, httptest.NewRequest(http.MethodGet, "/nope", nil))
|
||||||
|
if resp.StatusCode != 404 || body["error"] == nil {
|
||||||
|
t.Errorf("404 = %d %v, want JSON error", resp.StatusCode, body)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRateLimitPerClientBehindProxy(t *testing.T) {
|
||||||
|
jobs := &fakeJobs{nextID: newJobID(t), statuses: map[printqueue.JobID]printqueue.Status{}}
|
||||||
|
s := New(Config{
|
||||||
|
Info: Info{Project: "Überbringer"},
|
||||||
|
Secret: testSecret,
|
||||||
|
RateLimit: 2,
|
||||||
|
RateWindow: time.Minute,
|
||||||
|
TrustedProxies: []string{"0.0.0.0/0"},
|
||||||
|
ProxyHeader: "X-Real-IP",
|
||||||
|
BodyLimit: 1 << 20,
|
||||||
|
ReadTimeout: time.Second,
|
||||||
|
WriteTimeout: time.Second,
|
||||||
|
IdleTimeout: time.Second,
|
||||||
|
RequestID: func() string { return "req_test" },
|
||||||
|
}, jobs, fakePrinter{}, slog.New(slog.NewTextHandler(io.Discard, nil)))
|
||||||
|
|
||||||
|
send := func(clientIP string) int {
|
||||||
|
req := printRequest(t, validJob, "Bearer "+validToken(t))
|
||||||
|
req.Header.Set("X-Real-IP", clientIP)
|
||||||
|
resp, _ := do(t, s, req)
|
||||||
|
return resp.StatusCode
|
||||||
|
}
|
||||||
|
for range 2 {
|
||||||
|
if code := send("203.0.113.1"); code != http.StatusAccepted {
|
||||||
|
t.Fatalf("status = %d, want 202", code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if code := send("203.0.113.1"); code != http.StatusTooManyRequests {
|
||||||
|
t.Errorf("third request status = %d, want 429", code)
|
||||||
|
}
|
||||||
|
if code := send("203.0.113.2"); code != http.StatusAccepted {
|
||||||
|
t.Errorf("other client status = %d, want 202 (limits must be per client)", code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBearerToken(t *testing.T) {
|
||||||
|
tests := map[string]struct {
|
||||||
|
token string
|
||||||
|
ok bool
|
||||||
|
}{
|
||||||
|
"Bearer abc": {"abc", true},
|
||||||
|
"BEARER abc": {"abc", true},
|
||||||
|
"Bearer ": {"", false},
|
||||||
|
"Bearer": {"", false},
|
||||||
|
"Basic abc": {"", false},
|
||||||
|
"Bearer abc ": {"abc", true},
|
||||||
|
}
|
||||||
|
for header, want := range tests {
|
||||||
|
got, ok := bearerToken(header)
|
||||||
|
if got != want.token || ok != want.ok {
|
||||||
|
t.Errorf("bearerToken(%q) = %q, %v; want %q, %v", header, got, ok, want.token, want.ok)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,270 @@
|
|||||||
|
// Package config loads and validates the Überbringer daemon configuration
|
||||||
|
// from a TOML file.
|
||||||
|
package config
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"net/netip"
|
||||||
|
"os"
|
||||||
|
"slices"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/BurntSushi/toml"
|
||||||
|
)
|
||||||
|
|
||||||
|
// MinSecretLength is the minimum API secret length in bytes. HS256 keys
|
||||||
|
// shorter than the 256-bit hash output weaken the signature (RFC 7518 §3.2).
|
||||||
|
const MinSecretLength = 32
|
||||||
|
|
||||||
|
// Log formats accepted by [LogConfig.Format].
|
||||||
|
const (
|
||||||
|
LogFormatText = "text"
|
||||||
|
LogFormatJSON = "json"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Config is the root daemon configuration.
|
||||||
|
type Config struct {
|
||||||
|
WebServer WebServerConfig `toml:"webserver"`
|
||||||
|
API APIConfig `toml:"api"`
|
||||||
|
Printer PrinterConfig `toml:"printer"`
|
||||||
|
Queue QueueConfig `toml:"queue"`
|
||||||
|
Images ImagesConfig `toml:"images"`
|
||||||
|
Sentry SentryConfig `toml:"sentry"`
|
||||||
|
Log LogConfig `toml:"log"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// WebServerConfig configures the HTTP listener.
|
||||||
|
type WebServerConfig struct {
|
||||||
|
BindIP string `toml:"bind_ip"`
|
||||||
|
Port int `toml:"port"`
|
||||||
|
|
||||||
|
// RateLimit is the number of API requests one client may make per
|
||||||
|
// RateWindow.
|
||||||
|
RateLimit int `toml:"rate_limit"`
|
||||||
|
RateWindow time.Duration `toml:"rate_window"`
|
||||||
|
|
||||||
|
// TrustedProxies lists proxy IPs or CIDR ranges whose ProxyHeader is
|
||||||
|
// trusted to carry the real client IP.
|
||||||
|
TrustedProxies []string `toml:"trusted_proxies"`
|
||||||
|
ProxyHeader string `toml:"proxy_header"`
|
||||||
|
|
||||||
|
// BodyLimit is the maximum request body size in bytes.
|
||||||
|
BodyLimit int `toml:"body_limit"`
|
||||||
|
|
||||||
|
ReadTimeout time.Duration `toml:"read_timeout"`
|
||||||
|
WriteTimeout time.Duration `toml:"write_timeout"`
|
||||||
|
IdleTimeout time.Duration `toml:"idle_timeout"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// APIConfig configures API authentication.
|
||||||
|
type APIConfig struct {
|
||||||
|
// Secret is the HS256 key used to verify bearer tokens.
|
||||||
|
Secret string `toml:"secret"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// PrinterConfig configures the network receipt printer.
|
||||||
|
type PrinterConfig struct {
|
||||||
|
Address string `toml:"address"`
|
||||||
|
Port int `toml:"port"`
|
||||||
|
|
||||||
|
// Model selects a printer profile, e.g. "tm-t20" or "generic-58mm".
|
||||||
|
Model string `toml:"model"`
|
||||||
|
|
||||||
|
// CodePage is the character table text is transcoded to, e.g. "cp437".
|
||||||
|
CodePage string `toml:"codepage"`
|
||||||
|
|
||||||
|
// PaperWidth overrides the profile's printable width in dots. Zero keeps
|
||||||
|
// the profile default.
|
||||||
|
PaperWidth int `toml:"paper_width"`
|
||||||
|
|
||||||
|
// Columns overrides the number of Font A characters per line used for
|
||||||
|
// word wrapping. Zero derives it from the paper width.
|
||||||
|
Columns int `toml:"columns"`
|
||||||
|
|
||||||
|
DialTimeout time.Duration `toml:"dial_timeout"`
|
||||||
|
WriteTimeout time.Duration `toml:"write_timeout"`
|
||||||
|
|
||||||
|
// Retries is how many times a failed send is retried before the job is
|
||||||
|
// marked failed.
|
||||||
|
Retries int `toml:"retries"`
|
||||||
|
RetryDelay time.Duration `toml:"retry_delay"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// QueueConfig configures the print queue.
|
||||||
|
type QueueConfig struct {
|
||||||
|
// Size is the number of jobs that may wait to be printed.
|
||||||
|
Size int `toml:"size"`
|
||||||
|
|
||||||
|
// History is the number of finished jobs whose status is kept.
|
||||||
|
History int `toml:"history"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ImagesConfig configures image elements.
|
||||||
|
type ImagesConfig struct {
|
||||||
|
Timeout time.Duration `toml:"timeout"`
|
||||||
|
MaxBytes int64 `toml:"max_bytes"`
|
||||||
|
|
||||||
|
// MaxPixels caps the decoded image size to guard against decompression
|
||||||
|
// bombs.
|
||||||
|
MaxPixels int `toml:"max_pixels"`
|
||||||
|
|
||||||
|
// MaxHeight caps the printed image height in dots after scaling.
|
||||||
|
MaxHeight int `toml:"max_height"`
|
||||||
|
|
||||||
|
// AllowPrivateNetworks permits fetching from loopback, private and
|
||||||
|
// link-local addresses.
|
||||||
|
AllowPrivateNetworks bool `toml:"allow_private_networks"`
|
||||||
|
|
||||||
|
// AllowedHosts, when non-empty, restricts fetching to these hosts. Listed
|
||||||
|
// hosts may resolve to private addresses.
|
||||||
|
AllowedHosts []string `toml:"allowed_hosts"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// SentryConfig configures error reporting.
|
||||||
|
type SentryConfig struct {
|
||||||
|
DSN string `toml:"dsn"`
|
||||||
|
Environment string `toml:"environment"`
|
||||||
|
Debug bool `toml:"debug"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// LogConfig configures structured logging.
|
||||||
|
type LogConfig struct {
|
||||||
|
Level string `toml:"level"`
|
||||||
|
Format string `toml:"format"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Default returns a configuration with every optional setting at its
|
||||||
|
// default. API.Secret and Printer.Address have no defaults.
|
||||||
|
func Default() Config {
|
||||||
|
return Config{
|
||||||
|
WebServer: WebServerConfig{
|
||||||
|
BindIP: "127.0.0.1",
|
||||||
|
Port: 8080,
|
||||||
|
RateLimit: 60,
|
||||||
|
RateWindow: time.Minute,
|
||||||
|
TrustedProxies: []string{"127.0.0.1", "::1"},
|
||||||
|
ProxyHeader: "X-Real-IP",
|
||||||
|
BodyLimit: 4 << 20,
|
||||||
|
ReadTimeout: 15 * time.Second,
|
||||||
|
WriteTimeout: 15 * time.Second,
|
||||||
|
IdleTimeout: 60 * time.Second,
|
||||||
|
},
|
||||||
|
Printer: PrinterConfig{
|
||||||
|
Port: 9100,
|
||||||
|
Model: "tm-t20",
|
||||||
|
CodePage: "cp437",
|
||||||
|
DialTimeout: 5 * time.Second,
|
||||||
|
WriteTimeout: 30 * time.Second,
|
||||||
|
Retries: 3,
|
||||||
|
RetryDelay: time.Second,
|
||||||
|
},
|
||||||
|
Queue: QueueConfig{
|
||||||
|
Size: 100,
|
||||||
|
History: 1000,
|
||||||
|
},
|
||||||
|
Images: ImagesConfig{
|
||||||
|
Timeout: 10 * time.Second,
|
||||||
|
MaxBytes: 10 << 20,
|
||||||
|
MaxPixels: 25_000_000,
|
||||||
|
MaxHeight: 4000,
|
||||||
|
},
|
||||||
|
Sentry: SentryConfig{
|
||||||
|
Environment: "production",
|
||||||
|
},
|
||||||
|
Log: LogConfig{
|
||||||
|
Level: "info",
|
||||||
|
Format: LogFormatText,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Load reads the TOML file at path on top of [Default] and validates the
|
||||||
|
// result. Keys not recognised by Config are reported as errors so typos do not
|
||||||
|
// silently fall back to defaults. When sentry.dsn is unset, the SENTRY_DSN
|
||||||
|
// environment variable is used.
|
||||||
|
func Load(path string) (*Config, error) {
|
||||||
|
cfg := Default()
|
||||||
|
meta, err := toml.DecodeFile(path, &cfg)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("reading config %s: %w", path, err)
|
||||||
|
}
|
||||||
|
if undecoded := meta.Undecoded(); len(undecoded) > 0 {
|
||||||
|
keys := make([]string, len(undecoded))
|
||||||
|
for i, key := range undecoded {
|
||||||
|
keys[i] = key.String()
|
||||||
|
}
|
||||||
|
return nil, fmt.Errorf("config %s: unknown keys: %s", path, strings.Join(keys, ", "))
|
||||||
|
}
|
||||||
|
if cfg.Sentry.DSN == "" {
|
||||||
|
cfg.Sentry.DSN = os.Getenv("SENTRY_DSN")
|
||||||
|
}
|
||||||
|
if err := cfg.Validate(); err != nil {
|
||||||
|
return nil, fmt.Errorf("config %s: %w", path, err)
|
||||||
|
}
|
||||||
|
return &cfg, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate reports every problem with the configuration.
|
||||||
|
func (c *Config) Validate() error {
|
||||||
|
var errs []error
|
||||||
|
check := func(ok bool, format string, args ...any) {
|
||||||
|
if !ok {
|
||||||
|
errs = append(errs, fmt.Errorf(format, args...))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ws := c.WebServer
|
||||||
|
_, ipErr := netip.ParseAddr(ws.BindIP)
|
||||||
|
check(ipErr == nil, "webserver.bind_ip: %q is not an IP address", ws.BindIP)
|
||||||
|
check(validPort(ws.Port), "webserver.port: %d is out of range 1-65535", ws.Port)
|
||||||
|
check(ws.RateLimit > 0, "webserver.rate_limit must be positive")
|
||||||
|
check(ws.RateWindow > 0, "webserver.rate_window must be positive")
|
||||||
|
check(ws.BodyLimit > 0, "webserver.body_limit must be positive")
|
||||||
|
check(ws.ReadTimeout > 0 && ws.WriteTimeout > 0 && ws.IdleTimeout > 0,
|
||||||
|
"webserver read/write/idle timeouts must be positive")
|
||||||
|
for _, proxy := range ws.TrustedProxies {
|
||||||
|
check(validIPOrPrefix(proxy), "webserver.trusted_proxies: %q is not an IP or CIDR", proxy)
|
||||||
|
}
|
||||||
|
|
||||||
|
check(len(c.API.Secret) >= MinSecretLength,
|
||||||
|
"api.secret must be at least %d bytes (generate one with `uberbringer secret`)", MinSecretLength)
|
||||||
|
|
||||||
|
p := c.Printer
|
||||||
|
check(p.Address != "", "printer.address is required")
|
||||||
|
check(validPort(p.Port), "printer.port: %d is out of range 1-65535", p.Port)
|
||||||
|
check(p.PaperWidth >= 0, "printer.paper_width must not be negative")
|
||||||
|
check(p.Columns >= 0, "printer.columns must not be negative")
|
||||||
|
check(p.DialTimeout > 0 && p.WriteTimeout > 0, "printer dial/write timeouts must be positive")
|
||||||
|
check(p.Retries >= 0, "printer.retries must not be negative")
|
||||||
|
check(p.RetryDelay > 0, "printer.retry_delay must be positive")
|
||||||
|
|
||||||
|
check(c.Queue.Size > 0, "queue.size must be positive")
|
||||||
|
check(c.Queue.History >= 0, "queue.history must not be negative")
|
||||||
|
|
||||||
|
img := c.Images
|
||||||
|
check(img.Timeout > 0, "images.timeout must be positive")
|
||||||
|
check(img.MaxBytes > 0, "images.max_bytes must be positive")
|
||||||
|
check(img.MaxPixels > 0, "images.max_pixels must be positive")
|
||||||
|
check(img.MaxHeight > 0, "images.max_height must be positive")
|
||||||
|
|
||||||
|
check(slices.Contains([]string{"debug", "info", "warn", "error"}, c.Log.Level),
|
||||||
|
"log.level: %q must be one of debug, info, warn, error", c.Log.Level)
|
||||||
|
check(c.Log.Format == LogFormatText || c.Log.Format == LogFormatJSON,
|
||||||
|
"log.format: %q must be %q or %q", c.Log.Format, LogFormatText, LogFormatJSON)
|
||||||
|
|
||||||
|
return errors.Join(errs...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func validPort(port int) bool {
|
||||||
|
return port >= 1 && port <= 65535
|
||||||
|
}
|
||||||
|
|
||||||
|
func validIPOrPrefix(s string) bool {
|
||||||
|
if _, err := netip.ParseAddr(s); err == nil {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
_, err := netip.ParsePrefix(s)
|
||||||
|
return err == nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,173 @@
|
|||||||
|
package config_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/config"
|
||||||
|
)
|
||||||
|
|
||||||
|
const validSecret = "xTw8qdxTy7Ng4DiptTqmeVy506xWLht3OhFn4kdawmM="
|
||||||
|
|
||||||
|
func writeConfig(t *testing.T, body string) string {
|
||||||
|
t.Helper()
|
||||||
|
path := filepath.Join(t.TempDir(), "config.toml")
|
||||||
|
if err := os.WriteFile(path, []byte(body), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return path
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLoadLegacyConfigGetsDefaults(t *testing.T) {
|
||||||
|
t.Setenv("SENTRY_DSN", "")
|
||||||
|
// The exact shape written by the original install.sh, plus a printer.
|
||||||
|
path := writeConfig(t, `
|
||||||
|
[webserver]
|
||||||
|
bind_ip = "127.0.0.1"
|
||||||
|
port = 8080
|
||||||
|
|
||||||
|
[api]
|
||||||
|
secret = "`+validSecret+`"
|
||||||
|
|
||||||
|
[printer]
|
||||||
|
address = "192.168.1.245"
|
||||||
|
`)
|
||||||
|
cfg, err := config.Load(path)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Load: %v", err)
|
||||||
|
}
|
||||||
|
if cfg.Printer.Port != 9100 || cfg.Printer.Model != "tm-t20" || cfg.Printer.CodePage != "cp437" {
|
||||||
|
t.Errorf("printer defaults not applied: %+v", cfg.Printer)
|
||||||
|
}
|
||||||
|
if cfg.WebServer.RateWindow != time.Minute || cfg.Queue.Size != 100 {
|
||||||
|
t.Errorf("defaults not applied: %+v %+v", cfg.WebServer, cfg.Queue)
|
||||||
|
}
|
||||||
|
if cfg.Images.AllowPrivateNetworks {
|
||||||
|
t.Error("private networks must be blocked by default")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLoadOverridesAndDurations(t *testing.T) {
|
||||||
|
path := writeConfig(t, `
|
||||||
|
[api]
|
||||||
|
secret = "`+validSecret+`"
|
||||||
|
[printer]
|
||||||
|
address = "printer.lan"
|
||||||
|
dial_timeout = "750ms"
|
||||||
|
paper_width = 384
|
||||||
|
[images]
|
||||||
|
allowed_hosts = ["images.lan"]
|
||||||
|
[sentry]
|
||||||
|
dsn = "https://key@sentry.example/1"
|
||||||
|
[log]
|
||||||
|
format = "json"
|
||||||
|
`)
|
||||||
|
cfg, err := config.Load(path)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Load: %v", err)
|
||||||
|
}
|
||||||
|
if cfg.Printer.DialTimeout != 750*time.Millisecond {
|
||||||
|
t.Errorf("DialTimeout = %v, want 750ms", cfg.Printer.DialTimeout)
|
||||||
|
}
|
||||||
|
if cfg.Printer.PaperWidth != 384 || cfg.Log.Format != "json" {
|
||||||
|
t.Errorf("overrides not applied: %+v %+v", cfg.Printer, cfg.Log)
|
||||||
|
}
|
||||||
|
if len(cfg.Images.AllowedHosts) != 1 || cfg.Images.AllowedHosts[0] != "images.lan" {
|
||||||
|
t.Errorf("AllowedHosts = %v", cfg.Images.AllowedHosts)
|
||||||
|
}
|
||||||
|
if cfg.Sentry.DSN != "https://key@sentry.example/1" {
|
||||||
|
t.Errorf("DSN = %q", cfg.Sentry.DSN)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLoadSentryDSNFromEnvironment(t *testing.T) {
|
||||||
|
t.Setenv("SENTRY_DSN", "https://env@sentry.example/2")
|
||||||
|
path := writeConfig(t, "[api]\nsecret = \""+validSecret+"\"\n[printer]\naddress = \"p\"\n")
|
||||||
|
cfg, err := config.Load(path)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Load: %v", err)
|
||||||
|
}
|
||||||
|
if cfg.Sentry.DSN != "https://env@sentry.example/2" {
|
||||||
|
t.Errorf("DSN = %q, want value from SENTRY_DSN", cfg.Sentry.DSN)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLoadErrors(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
body string
|
||||||
|
wantErr string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "missing secret",
|
||||||
|
body: "[printer]\naddress = \"p\"\n",
|
||||||
|
wantErr: "api.secret must be at least 32 bytes",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "short secret",
|
||||||
|
body: "[api]\nsecret = \"short\"\n[printer]\naddress = \"p\"\n",
|
||||||
|
wantErr: "api.secret must be at least 32 bytes",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "missing printer address",
|
||||||
|
body: "[api]\nsecret = \"" + validSecret + "\"\n",
|
||||||
|
wantErr: "printer.address is required",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "unknown key",
|
||||||
|
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\nadress = \"typo\"\n",
|
||||||
|
wantErr: "unknown keys: printer.adress",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "bad duration",
|
||||||
|
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\ndial_timeout = \"soon\"\n",
|
||||||
|
wantErr: "dial_timeout",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "bad trusted proxy",
|
||||||
|
body: "[webserver]\ntrusted_proxies = [\"nginx\"]\n[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n",
|
||||||
|
wantErr: `"nginx" is not an IP or CIDR`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "bad log level",
|
||||||
|
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[log]\nlevel = \"loud\"\n",
|
||||||
|
wantErr: "log.level",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
_, err := config.Load(writeConfig(t, tt.body))
|
||||||
|
if err == nil || !strings.Contains(err.Error(), tt.wantErr) {
|
||||||
|
t.Fatalf("Load error = %v, want it to contain %q", err, tt.wantErr)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The documented example must stay loadable: every key in it must exist.
|
||||||
|
func TestExampleConfigLoads(t *testing.T) {
|
||||||
|
example, err := os.ReadFile(filepath.Join("..", "..", "..", "configs", "config.example.toml"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
body := strings.Replace(string(example), `secret = ""`, `secret = "`+validSecret+`"`, 1)
|
||||||
|
body = strings.Replace(body, `address = ""`, `address = "192.168.1.245"`, 1)
|
||||||
|
cfg, err := config.Load(writeConfig(t, body))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("example config: %v", err)
|
||||||
|
}
|
||||||
|
if def := config.Default(); cfg.WebServer.RateLimit != def.WebServer.RateLimit ||
|
||||||
|
cfg.Images.MaxBytes != def.Images.MaxBytes || cfg.Printer.Model != def.Printer.Model {
|
||||||
|
t.Error("example config values drifted from the defaults it documents")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLoadMissingFile(t *testing.T) {
|
||||||
|
_, err := config.Load(filepath.Join(t.TempDir(), "nope.toml"))
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("expected error for missing file")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,211 @@
|
|||||||
|
package escpos
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Symbology identifies a one-dimensional barcode type. Values are the GS k
|
||||||
|
// function B type codes.
|
||||||
|
type Symbology byte
|
||||||
|
|
||||||
|
// Supported barcode symbologies.
|
||||||
|
const (
|
||||||
|
UPCA Symbology = 65
|
||||||
|
UPCE Symbology = 66
|
||||||
|
EAN13 Symbology = 67
|
||||||
|
EAN8 Symbology = 68
|
||||||
|
CODE39 Symbology = 69
|
||||||
|
CODE128 Symbology = 73
|
||||||
|
)
|
||||||
|
|
||||||
|
// HRIPosition places the human-readable interpretation (the digits) relative
|
||||||
|
// to a barcode.
|
||||||
|
type HRIPosition byte
|
||||||
|
|
||||||
|
// HRIPosition values for GS H.
|
||||||
|
const (
|
||||||
|
HRINone HRIPosition = 0
|
||||||
|
HRIAbove HRIPosition = 1
|
||||||
|
HRIBelow HRIPosition = 2
|
||||||
|
HRIBoth HRIPosition = 3
|
||||||
|
)
|
||||||
|
|
||||||
|
// Barcode module width limits for GS w.
|
||||||
|
const (
|
||||||
|
MinBarcodeWidth = 2
|
||||||
|
MaxBarcodeWidth = 6
|
||||||
|
)
|
||||||
|
|
||||||
|
const code39Charset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ -.$/+%"
|
||||||
|
|
||||||
|
// ParseSymbology returns the symbology named by name, e.g. "ean13".
|
||||||
|
func ParseSymbology(name string) (Symbology, error) {
|
||||||
|
switch strings.ToLower(strings.TrimSpace(name)) {
|
||||||
|
case "upca", "upc-a":
|
||||||
|
return UPCA, nil
|
||||||
|
case "upce", "upc-e":
|
||||||
|
return UPCE, nil
|
||||||
|
case "ean13", "ean-13", "jan13":
|
||||||
|
return EAN13, nil
|
||||||
|
case "ean8", "ean-8", "jan8":
|
||||||
|
return EAN8, nil
|
||||||
|
case "code39", "code-39":
|
||||||
|
return CODE39, nil
|
||||||
|
case "code128", "code-128":
|
||||||
|
return CODE128, nil
|
||||||
|
}
|
||||||
|
return 0, fmt.Errorf("%w: unknown barcode symbology %q", ErrInvalidArgument, name)
|
||||||
|
}
|
||||||
|
|
||||||
|
// String returns the canonical symbology name.
|
||||||
|
func (s Symbology) String() string {
|
||||||
|
switch s {
|
||||||
|
case UPCA:
|
||||||
|
return "upca"
|
||||||
|
case UPCE:
|
||||||
|
return "upce"
|
||||||
|
case EAN13:
|
||||||
|
return "ean13"
|
||||||
|
case EAN8:
|
||||||
|
return "ean8"
|
||||||
|
case CODE39:
|
||||||
|
return "code39"
|
||||||
|
case CODE128:
|
||||||
|
return "code128"
|
||||||
|
}
|
||||||
|
return fmt.Sprintf("Symbology(%d)", byte(s))
|
||||||
|
}
|
||||||
|
|
||||||
|
// ValidateBarcode reports whether data can be encoded as sym. Where data
|
||||||
|
// includes the check digit, the check digit is verified.
|
||||||
|
func ValidateBarcode(sym Symbology, data string) error {
|
||||||
|
invalid := func(format string, args ...any) error {
|
||||||
|
return fmt.Errorf("%w: %s: "+format, append([]any{ErrInvalidArgument, sym}, args...)...)
|
||||||
|
}
|
||||||
|
switch sym {
|
||||||
|
case UPCA:
|
||||||
|
if !isDigits(data) || (len(data) != 11 && len(data) != 12) {
|
||||||
|
return invalid("want 11 or 12 digits")
|
||||||
|
}
|
||||||
|
if len(data) == 12 && !validCheckDigit(data) {
|
||||||
|
return invalid("check digit is wrong")
|
||||||
|
}
|
||||||
|
case UPCE:
|
||||||
|
switch {
|
||||||
|
case !isDigits(data):
|
||||||
|
return invalid("want digits only")
|
||||||
|
case len(data) >= 6 && len(data) <= 8:
|
||||||
|
case (len(data) == 11 || len(data) == 12) && data[0] == '0':
|
||||||
|
default:
|
||||||
|
return invalid("want 6-8 digits, or 11-12 digits starting with 0")
|
||||||
|
}
|
||||||
|
case EAN13:
|
||||||
|
if !isDigits(data) || (len(data) != 12 && len(data) != 13) {
|
||||||
|
return invalid("want 12 or 13 digits")
|
||||||
|
}
|
||||||
|
if len(data) == 13 && !validCheckDigit(data) {
|
||||||
|
return invalid("check digit is wrong")
|
||||||
|
}
|
||||||
|
case EAN8:
|
||||||
|
if !isDigits(data) || (len(data) != 7 && len(data) != 8) {
|
||||||
|
return invalid("want 7 or 8 digits")
|
||||||
|
}
|
||||||
|
if len(data) == 8 && !validCheckDigit(data) {
|
||||||
|
return invalid("check digit is wrong")
|
||||||
|
}
|
||||||
|
case CODE39:
|
||||||
|
if len(data) < 1 || len(data) > 255 {
|
||||||
|
return invalid("want 1-255 characters")
|
||||||
|
}
|
||||||
|
for _, r := range data {
|
||||||
|
if !strings.ContainsRune(code39Charset, r) {
|
||||||
|
return invalid("character %q not allowed (use 0-9, A-Z, space and -.$/+%%)", r)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case CODE128:
|
||||||
|
if len(data) < 1 {
|
||||||
|
return invalid("data is empty")
|
||||||
|
}
|
||||||
|
for _, r := range data {
|
||||||
|
if r < 0x20 || r > 0x7E {
|
||||||
|
return invalid("character %q not allowed (printable ASCII only)", r)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(code128Payload(data)) > 255 {
|
||||||
|
return invalid("data is too long")
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
return fmt.Errorf("%w: unknown barcode symbology %d", ErrInvalidArgument, byte(sym))
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// BarcodeHeight sets the barcode height in dots (GS h n).
|
||||||
|
func (b *Builder) BarcodeHeight(dots uint8) {
|
||||||
|
b.buf.Write([]byte{gs, 'h', dots})
|
||||||
|
}
|
||||||
|
|
||||||
|
// BarcodeWidth sets the barcode module width, [MinBarcodeWidth] to
|
||||||
|
// [MaxBarcodeWidth] (GS w n).
|
||||||
|
func (b *Builder) BarcodeWidth(module int) error {
|
||||||
|
if module < MinBarcodeWidth || module > MaxBarcodeWidth {
|
||||||
|
return fmt.Errorf("%w: barcode width %d must be within %d-%d",
|
||||||
|
ErrInvalidArgument, module, MinBarcodeWidth, MaxBarcodeWidth)
|
||||||
|
}
|
||||||
|
b.buf.Write([]byte{gs, 'w', byte(module)})
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// BarcodeHRI sets where the human-readable digits are printed (GS H n).
|
||||||
|
func (b *Builder) BarcodeHRI(pos HRIPosition) {
|
||||||
|
b.buf.Write([]byte{gs, 'H', byte(pos)})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Barcode validates data and appends a barcode (GS k m n d1...dn). CODE128
|
||||||
|
// data is printed in code set B, so callers pass plain text.
|
||||||
|
func (b *Builder) Barcode(sym Symbology, data string) error {
|
||||||
|
if err := ValidateBarcode(sym, data); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
payload := []byte(data)
|
||||||
|
if sym == CODE128 {
|
||||||
|
payload = code128Payload(data)
|
||||||
|
}
|
||||||
|
b.buf.Write([]byte{gs, 'k', byte(sym), byte(len(payload))})
|
||||||
|
b.buf.Write(payload)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// code128Payload selects code set B and escapes '{', which the printer
|
||||||
|
// treats as the start of a code set or function character.
|
||||||
|
func code128Payload(data string) []byte {
|
||||||
|
return []byte("{B" + strings.ReplaceAll(data, "{", "{{"))
|
||||||
|
}
|
||||||
|
|
||||||
|
func isDigits(s string) bool {
|
||||||
|
if s == "" {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for i := range len(s) {
|
||||||
|
if s[i] < '0' || s[i] > '9' {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// validCheckDigit verifies the GS1 mod-10 check digit in the last position of
|
||||||
|
// a UPC-A, EAN-13 or EAN-8 number.
|
||||||
|
func validCheckDigit(code string) bool {
|
||||||
|
sum := 0
|
||||||
|
body := code[:len(code)-1]
|
||||||
|
for i := range len(body) {
|
||||||
|
digit := int(body[len(body)-1-i] - '0')
|
||||||
|
if i%2 == 0 {
|
||||||
|
digit *= 3
|
||||||
|
}
|
||||||
|
sum += digit
|
||||||
|
}
|
||||||
|
return (10-sum%10)%10 == int(code[len(code)-1]-'0')
|
||||||
|
}
|
||||||
@@ -0,0 +1,181 @@
|
|||||||
|
// Package escpos builds Epson ESC/POS command streams for thermal receipt
|
||||||
|
// printers.
|
||||||
|
//
|
||||||
|
// A [Builder] accumulates commands in memory. Callers send [Builder.Bytes] to
|
||||||
|
// the printer in a single write, so an invalid element never leaves a
|
||||||
|
// half-printed receipt. Commands follow the Epson ESC/POS Application
|
||||||
|
// Programming Guide; byte values are named by the control characters the
|
||||||
|
// specification uses (ESC, GS, DLE).
|
||||||
|
package escpos
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Control characters that introduce ESC/POS commands.
|
||||||
|
const (
|
||||||
|
ht byte = 0x09
|
||||||
|
lf byte = 0x0A
|
||||||
|
dle byte = 0x10
|
||||||
|
eot byte = 0x04
|
||||||
|
esc byte = 0x1B
|
||||||
|
gs byte = 0x1D
|
||||||
|
)
|
||||||
|
|
||||||
|
// MaxCharacterScale is the largest character width or height multiplier
|
||||||
|
// supported by GS !.
|
||||||
|
const MaxCharacterScale = 8
|
||||||
|
|
||||||
|
// ErrInvalidArgument is wrapped by every validation error the package
|
||||||
|
// returns.
|
||||||
|
var ErrInvalidArgument = errors.New("escpos: invalid argument")
|
||||||
|
|
||||||
|
// Justification aligns text, barcodes and QR codes on the line.
|
||||||
|
type Justification byte
|
||||||
|
|
||||||
|
// Justification values for ESC a.
|
||||||
|
const (
|
||||||
|
JustifyLeft Justification = 0
|
||||||
|
JustifyCenter Justification = 1
|
||||||
|
JustifyRight Justification = 2
|
||||||
|
)
|
||||||
|
|
||||||
|
// Font selects one of the printer's built-in character fonts.
|
||||||
|
type Font byte
|
||||||
|
|
||||||
|
// Font values for ESC M.
|
||||||
|
const (
|
||||||
|
FontA Font = 0
|
||||||
|
FontB Font = 1
|
||||||
|
)
|
||||||
|
|
||||||
|
// Underline selects the underline thickness.
|
||||||
|
type Underline byte
|
||||||
|
|
||||||
|
// Underline values for ESC -.
|
||||||
|
const (
|
||||||
|
UnderlineNone Underline = 0
|
||||||
|
UnderlineThin Underline = 1
|
||||||
|
UnderlineThick Underline = 2
|
||||||
|
)
|
||||||
|
|
||||||
|
// CutMode selects a full or partial paper cut.
|
||||||
|
type CutMode byte
|
||||||
|
|
||||||
|
// CutMode values for GS V function B, which feeds the paper to the cutting
|
||||||
|
// position before cutting so the last printed line is not lost.
|
||||||
|
const (
|
||||||
|
CutFull CutMode = 65
|
||||||
|
CutPartial CutMode = 66
|
||||||
|
)
|
||||||
|
|
||||||
|
// Builder accumulates an ESC/POS command stream. The zero value is ready to
|
||||||
|
// use. A Builder is not safe for concurrent use.
|
||||||
|
type Builder struct {
|
||||||
|
buf bytes.Buffer
|
||||||
|
}
|
||||||
|
|
||||||
|
// Bytes returns the accumulated command stream. The slice aliases the
|
||||||
|
// Builder's buffer and is valid until the next write.
|
||||||
|
func (b *Builder) Bytes() []byte {
|
||||||
|
return b.buf.Bytes()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Len returns the number of accumulated bytes.
|
||||||
|
func (b *Builder) Len() int {
|
||||||
|
return b.buf.Len()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Raw appends p unchanged. It is the escape hatch for commands the Builder
|
||||||
|
// does not model.
|
||||||
|
func (b *Builder) Raw(p []byte) {
|
||||||
|
b.buf.Write(p)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Text appends already-encoded character data. Use [CodePage.Encode] to
|
||||||
|
// convert UTF-8 text first.
|
||||||
|
func (b *Builder) Text(encoded []byte) {
|
||||||
|
b.buf.Write(encoded)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Initialize resets the printer to its power-on settings (ESC @).
|
||||||
|
func (b *Builder) Initialize() {
|
||||||
|
b.buf.Write([]byte{esc, '@'})
|
||||||
|
}
|
||||||
|
|
||||||
|
// LineFeed prints the line buffer and advances one line (LF).
|
||||||
|
func (b *Builder) LineFeed() {
|
||||||
|
b.buf.WriteByte(lf)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Feed prints the line buffer and advances lines lines (ESC d n).
|
||||||
|
func (b *Builder) Feed(lines uint8) {
|
||||||
|
b.buf.Write([]byte{esc, 'd', lines})
|
||||||
|
}
|
||||||
|
|
||||||
|
// LineSpacing sets the line spacing in motion units (ESC 3 n).
|
||||||
|
func (b *Builder) LineSpacing(units uint8) {
|
||||||
|
b.buf.Write([]byte{esc, '3', units})
|
||||||
|
}
|
||||||
|
|
||||||
|
// DefaultLineSpacing restores the default line spacing (ESC 2).
|
||||||
|
func (b *Builder) DefaultLineSpacing() {
|
||||||
|
b.buf.Write([]byte{esc, '2'})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Bold turns emphasized printing on or off (ESC E n).
|
||||||
|
func (b *Builder) Bold(on bool) {
|
||||||
|
b.buf.Write([]byte{esc, 'E', boolByte(on)})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Underline sets the underline mode (ESC - n).
|
||||||
|
func (b *Builder) Underline(u Underline) {
|
||||||
|
b.buf.Write([]byte{esc, '-', byte(u)})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reverse turns white-on-black printing on or off (GS B n).
|
||||||
|
func (b *Builder) Reverse(on bool) {
|
||||||
|
b.buf.Write([]byte{gs, 'B', boolByte(on)})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Justify sets the alignment (ESC a n). It takes effect at the start of the
|
||||||
|
// next line.
|
||||||
|
func (b *Builder) Justify(j Justification) {
|
||||||
|
b.buf.Write([]byte{esc, 'a', byte(j)})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Font selects the character font (ESC M n).
|
||||||
|
func (b *Builder) Font(f Font) {
|
||||||
|
b.buf.Write([]byte{esc, 'M', byte(f)})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Size sets the character width and height multipliers, each 1 to
|
||||||
|
// [MaxCharacterScale] (GS ! n).
|
||||||
|
func (b *Builder) Size(width, height int) error {
|
||||||
|
if width < 1 || width > MaxCharacterScale || height < 1 || height > MaxCharacterScale {
|
||||||
|
return fmt.Errorf("%w: character size %dx%d must be within 1-%d",
|
||||||
|
ErrInvalidArgument, width, height, MaxCharacterScale)
|
||||||
|
}
|
||||||
|
b.buf.Write([]byte{gs, '!', byte(width-1)<<4 | byte(height-1)})
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// SelectCodePage selects the character table used to print text (ESC t n).
|
||||||
|
func (b *Builder) SelectCodePage(cp CodePage) {
|
||||||
|
b.buf.Write([]byte{esc, 't', cp.table()})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Cut feeds the paper to the cutter plus feed motion units and cuts it
|
||||||
|
// (GS V m n).
|
||||||
|
func (b *Builder) Cut(mode CutMode, feed uint8) {
|
||||||
|
b.buf.Write([]byte{gs, 'V', byte(mode), feed})
|
||||||
|
}
|
||||||
|
|
||||||
|
func boolByte(on bool) byte {
|
||||||
|
if on {
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
@@ -0,0 +1,112 @@
|
|||||||
|
package escpos
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
"unicode/utf8"
|
||||||
|
|
||||||
|
"golang.org/x/text/encoding/charmap"
|
||||||
|
)
|
||||||
|
|
||||||
|
// CodePage is a printer character table. It ties the ESC t table number the
|
||||||
|
// printer understands to the character map used to transcode UTF-8 text, so
|
||||||
|
// the two can never disagree.
|
||||||
|
type CodePage int
|
||||||
|
|
||||||
|
// Supported code pages. CodePage437 is the Epson factory default.
|
||||||
|
const (
|
||||||
|
CodePage437 CodePage = iota + 1
|
||||||
|
CodePage850
|
||||||
|
CodePage858
|
||||||
|
CodePage1252
|
||||||
|
)
|
||||||
|
|
||||||
|
// ParseCodePage returns the code page named by name, e.g. "cp437".
|
||||||
|
func ParseCodePage(name string) (CodePage, error) {
|
||||||
|
switch strings.ToLower(strings.TrimSpace(name)) {
|
||||||
|
case "cp437", "437", "pc437":
|
||||||
|
return CodePage437, nil
|
||||||
|
case "cp850", "850", "pc850":
|
||||||
|
return CodePage850, nil
|
||||||
|
case "cp858", "858", "pc858":
|
||||||
|
return CodePage858, nil
|
||||||
|
case "cp1252", "1252", "wpc1252", "windows-1252":
|
||||||
|
return CodePage1252, nil
|
||||||
|
}
|
||||||
|
return 0, fmt.Errorf("%w: unknown code page %q (want cp437, cp850, cp858 or cp1252)",
|
||||||
|
ErrInvalidArgument, name)
|
||||||
|
}
|
||||||
|
|
||||||
|
// String returns the canonical code page name.
|
||||||
|
func (cp CodePage) String() string {
|
||||||
|
switch cp {
|
||||||
|
case CodePage437:
|
||||||
|
return "cp437"
|
||||||
|
case CodePage850:
|
||||||
|
return "cp850"
|
||||||
|
case CodePage858:
|
||||||
|
return "cp858"
|
||||||
|
case CodePage1252:
|
||||||
|
return "cp1252"
|
||||||
|
}
|
||||||
|
return fmt.Sprintf("CodePage(%d)", int(cp))
|
||||||
|
}
|
||||||
|
|
||||||
|
// table returns the ESC t table number for cp.
|
||||||
|
func (cp CodePage) table() byte {
|
||||||
|
switch cp {
|
||||||
|
case CodePage850:
|
||||||
|
return 2
|
||||||
|
case CodePage858:
|
||||||
|
return 19
|
||||||
|
case CodePage1252:
|
||||||
|
return 16
|
||||||
|
}
|
||||||
|
return 0 // PC437, also the fallback for an invalid CodePage.
|
||||||
|
}
|
||||||
|
|
||||||
|
func (cp CodePage) charmap() *charmap.Charmap {
|
||||||
|
switch cp {
|
||||||
|
case CodePage850:
|
||||||
|
return charmap.CodePage850
|
||||||
|
case CodePage858:
|
||||||
|
return charmap.CodePage858
|
||||||
|
case CodePage1252:
|
||||||
|
return charmap.Windows1252
|
||||||
|
}
|
||||||
|
return charmap.CodePage437
|
||||||
|
}
|
||||||
|
|
||||||
|
// Encode transcodes UTF-8 text to cp, one byte per rune. Runes the code page
|
||||||
|
// cannot represent become '?'. Control characters other than newline and tab
|
||||||
|
// are dropped, because the printer would interpret them as commands.
|
||||||
|
func (cp CodePage) Encode(s string) []byte {
|
||||||
|
cm := cp.charmap()
|
||||||
|
out := make([]byte, 0, len(s))
|
||||||
|
for _, r := range s {
|
||||||
|
switch {
|
||||||
|
case r == '\n' || r == '\t':
|
||||||
|
out = append(out, byte(r))
|
||||||
|
case IsControl(r):
|
||||||
|
// Dropped: control bytes would be read as printer commands.
|
||||||
|
case r < utf8.RuneSelf:
|
||||||
|
out = append(out, byte(r))
|
||||||
|
default:
|
||||||
|
c, ok := cm.EncodeRune(r)
|
||||||
|
if !ok || c < 0x20 || c == 0x7F {
|
||||||
|
c = '?'
|
||||||
|
}
|
||||||
|
out = append(out, c)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// IsControl reports whether r is a control character that [CodePage.Encode]
|
||||||
|
// drops. Newline and tab are not reported.
|
||||||
|
func IsControl(r rune) bool {
|
||||||
|
if r == '\n' || r == '\t' {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return r < 0x20 || r == 0x7F || (r >= 0x80 && r < 0xA0) || r == utf8.RuneError
|
||||||
|
}
|
||||||
@@ -0,0 +1,426 @@
|
|||||||
|
package escpos_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"errors"
|
||||||
|
"image"
|
||||||
|
"image/color"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/escpos"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Byte-exact checks against the Epson ESC/POS command reference.
|
||||||
|
func TestCommands(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
build func(b *escpos.Builder)
|
||||||
|
want []byte
|
||||||
|
}{
|
||||||
|
{"initialize", func(b *escpos.Builder) { b.Initialize() }, []byte{0x1B, 0x40}},
|
||||||
|
{"line feed", func(b *escpos.Builder) { b.LineFeed() }, []byte{0x0A}},
|
||||||
|
{"feed 3", func(b *escpos.Builder) { b.Feed(3) }, []byte{0x1B, 0x64, 3}},
|
||||||
|
{"line spacing", func(b *escpos.Builder) { b.LineSpacing(30) }, []byte{0x1B, 0x33, 30}},
|
||||||
|
{"default line spacing", func(b *escpos.Builder) { b.DefaultLineSpacing() }, []byte{0x1B, 0x32}},
|
||||||
|
{"bold on", func(b *escpos.Builder) { b.Bold(true) }, []byte{0x1B, 0x45, 1}},
|
||||||
|
{"bold off", func(b *escpos.Builder) { b.Bold(false) }, []byte{0x1B, 0x45, 0}},
|
||||||
|
{"underline thick", func(b *escpos.Builder) { b.Underline(escpos.UnderlineThick) }, []byte{0x1B, 0x2D, 2}},
|
||||||
|
{"reverse", func(b *escpos.Builder) { b.Reverse(true) }, []byte{0x1D, 0x42, 1}},
|
||||||
|
{"justify center", func(b *escpos.Builder) { b.Justify(escpos.JustifyCenter) }, []byte{0x1B, 0x61, 1}},
|
||||||
|
{"font b", func(b *escpos.Builder) { b.Font(escpos.FontB) }, []byte{0x1B, 0x4D, 1}},
|
||||||
|
{"code page 437", func(b *escpos.Builder) { b.SelectCodePage(escpos.CodePage437) }, []byte{0x1B, 0x74, 0}},
|
||||||
|
{"code page 850", func(b *escpos.Builder) { b.SelectCodePage(escpos.CodePage850) }, []byte{0x1B, 0x74, 2}},
|
||||||
|
{"code page 858", func(b *escpos.Builder) { b.SelectCodePage(escpos.CodePage858) }, []byte{0x1B, 0x74, 19}},
|
||||||
|
{"code page 1252", func(b *escpos.Builder) { b.SelectCodePage(escpos.CodePage1252) }, []byte{0x1B, 0x74, 16}},
|
||||||
|
{"partial cut", func(b *escpos.Builder) { b.Cut(escpos.CutPartial, 0) }, []byte{0x1D, 0x56, 66, 0}},
|
||||||
|
{"full cut", func(b *escpos.Builder) { b.Cut(escpos.CutFull, 5) }, []byte{0x1D, 0x56, 65, 5}},
|
||||||
|
{"barcode height", func(b *escpos.Builder) { b.BarcodeHeight(80) }, []byte{0x1D, 0x68, 80}},
|
||||||
|
{"barcode hri", func(b *escpos.Builder) { b.BarcodeHRI(escpos.HRIBelow) }, []byte{0x1D, 0x48, 2}},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
var b escpos.Builder
|
||||||
|
tt.build(&b)
|
||||||
|
if !bytes.Equal(b.Bytes(), tt.want) {
|
||||||
|
t.Errorf("got % X, want % X", b.Bytes(), tt.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSize(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
width, height int
|
||||||
|
want byte
|
||||||
|
wantErr bool
|
||||||
|
}{
|
||||||
|
{1, 1, 0x00, false},
|
||||||
|
{2, 2, 0x11, false},
|
||||||
|
{8, 8, 0x77, false},
|
||||||
|
{3, 1, 0x20, false},
|
||||||
|
{1, 4, 0x03, false},
|
||||||
|
{0, 1, 0, true},
|
||||||
|
{9, 1, 0, true},
|
||||||
|
{1, 9, 0, true},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
var b escpos.Builder
|
||||||
|
err := b.Size(tt.width, tt.height)
|
||||||
|
if tt.wantErr {
|
||||||
|
if !errors.Is(err, escpos.ErrInvalidArgument) || b.Len() != 0 {
|
||||||
|
t.Errorf("Size(%d,%d): err=%v len=%d, want ErrInvalidArgument and nothing written",
|
||||||
|
tt.width, tt.height, err, b.Len())
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
want := []byte{0x1D, 0x21, tt.want}
|
||||||
|
if err != nil || !bytes.Equal(b.Bytes(), want) {
|
||||||
|
t.Errorf("Size(%d,%d) = % X, %v; want % X", tt.width, tt.height, b.Bytes(), err, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBarcodeWidthUsesWidthCommand(t *testing.T) {
|
||||||
|
var b escpos.Builder
|
||||||
|
if err := b.BarcodeWidth(3); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if want := []byte{0x1D, 0x77, 3}; !bytes.Equal(b.Bytes(), want) {
|
||||||
|
t.Errorf("got % X, want % X", b.Bytes(), want)
|
||||||
|
}
|
||||||
|
if err := b.BarcodeWidth(7); !errors.Is(err, escpos.ErrInvalidArgument) {
|
||||||
|
t.Errorf("BarcodeWidth(7) err = %v, want ErrInvalidArgument", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBarcode(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
sym escpos.Symbology
|
||||||
|
data string
|
||||||
|
want []byte
|
||||||
|
wantErr bool
|
||||||
|
}{
|
||||||
|
{name: "ean13 with check digit", sym: escpos.EAN13, data: "4006381333931",
|
||||||
|
want: append([]byte{0x1D, 0x6B, 67, 13}, "4006381333931"...)},
|
||||||
|
{name: "ean13 without check digit", sym: escpos.EAN13, data: "400638133393",
|
||||||
|
want: append([]byte{0x1D, 0x6B, 67, 12}, "400638133393"...)},
|
||||||
|
{name: "ean13 wrong check digit", sym: escpos.EAN13, data: "4006381333932", wantErr: true},
|
||||||
|
{name: "ean13 letters", sym: escpos.EAN13, data: "40063813339A", wantErr: true},
|
||||||
|
{name: "ean8", sym: escpos.EAN8, data: "96385074",
|
||||||
|
want: append([]byte{0x1D, 0x6B, 68, 8}, "96385074"...)},
|
||||||
|
{name: "ean8 wrong length", sym: escpos.EAN8, data: "123", wantErr: true},
|
||||||
|
{name: "upca", sym: escpos.UPCA, data: "036000291452",
|
||||||
|
want: append([]byte{0x1D, 0x6B, 65, 12}, "036000291452"...)},
|
||||||
|
{name: "upce short", sym: escpos.UPCE, data: "123456",
|
||||||
|
want: append([]byte{0x1D, 0x6B, 66, 6}, "123456"...)},
|
||||||
|
{name: "upce long must start with 0", sym: escpos.UPCE, data: "12345678901", wantErr: true},
|
||||||
|
{name: "code39", sym: escpos.CODE39, data: "ABC-123",
|
||||||
|
want: append([]byte{0x1D, 0x6B, 69, 7}, "ABC-123"...)},
|
||||||
|
{name: "code39 lowercase", sym: escpos.CODE39, data: "abc", wantErr: true},
|
||||||
|
{name: "code128 code set B", sym: escpos.CODE128, data: "Hello-1",
|
||||||
|
want: append([]byte{0x1D, 0x6B, 73, 9}, "{BHello-1"...)},
|
||||||
|
{name: "code128 escapes brace", sym: escpos.CODE128, data: "a{b",
|
||||||
|
want: append([]byte{0x1D, 0x6B, 73, 6}, "{Ba{{b"...)},
|
||||||
|
{name: "code128 non-ascii", sym: escpos.CODE128, data: "Grüße", wantErr: true},
|
||||||
|
{name: "code128 too long", sym: escpos.CODE128, data: strings.Repeat("x", 254), wantErr: true},
|
||||||
|
{name: "empty", sym: escpos.CODE128, data: "", wantErr: true},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
var b escpos.Builder
|
||||||
|
err := b.Barcode(tt.sym, tt.data)
|
||||||
|
if tt.wantErr {
|
||||||
|
if !errors.Is(err, escpos.ErrInvalidArgument) || b.Len() != 0 {
|
||||||
|
t.Fatalf("err=%v len=%d, want ErrInvalidArgument and nothing written", err, b.Len())
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !bytes.Equal(b.Bytes(), tt.want) {
|
||||||
|
t.Errorf("got % X, want % X", b.Bytes(), tt.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestQRCode(t *testing.T) {
|
||||||
|
var b escpos.Builder
|
||||||
|
if err := b.QRCode([]byte("hi"), 6, escpos.QRCorrectionM); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
want := []byte{
|
||||||
|
0x1D, 0x28, 0x6B, 4, 0, 0x31, 0x41, 0x32, 0, // model 2
|
||||||
|
0x1D, 0x28, 0x6B, 3, 0, 0x31, 0x43, 6, // module size
|
||||||
|
0x1D, 0x28, 0x6B, 3, 0, 0x31, 0x45, 49, // correction M
|
||||||
|
0x1D, 0x28, 0x6B, 5, 0, 0x31, 0x50, 0x30, 'h', 'i', // store
|
||||||
|
0x1D, 0x28, 0x6B, 3, 0, 0x31, 0x51, 0x30, // print
|
||||||
|
}
|
||||||
|
if !bytes.Equal(b.Bytes(), want) {
|
||||||
|
t.Errorf("got % X\nwant % X", b.Bytes(), want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestQRCodeStoreLengthUsesHighByte(t *testing.T) {
|
||||||
|
var b escpos.Builder
|
||||||
|
data := bytes.Repeat([]byte{'x'}, 300)
|
||||||
|
if err := b.QRCode(data, 4, escpos.QRCorrectionL); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
store := []byte{0x1D, 0x28, 0x6B, byte(303 & 0xFF), byte(303 >> 8), 0x31, 0x50, 0x30}
|
||||||
|
if !bytes.Contains(b.Bytes(), store) {
|
||||||
|
t.Errorf("store header % X not found", store)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestQRCodeRejects(t *testing.T) {
|
||||||
|
tests := map[string]func(b *escpos.Builder) error{
|
||||||
|
"empty": func(b *escpos.Builder) error { return b.QRCode(nil, 4, escpos.QRCorrectionM) },
|
||||||
|
"too long": func(b *escpos.Builder) error {
|
||||||
|
return b.QRCode(make([]byte, escpos.MaxQRData+1), 4, escpos.QRCorrectionM)
|
||||||
|
},
|
||||||
|
"module too big": func(b *escpos.Builder) error { return b.QRCode([]byte("x"), 17, escpos.QRCorrectionM) },
|
||||||
|
"bad correction": func(b *escpos.Builder) error { return b.QRCode([]byte("x"), 4, 47) },
|
||||||
|
"module too small": func(b *escpos.Builder) error { return b.QRCode([]byte("x"), 0, escpos.QRCorrectionM) },
|
||||||
|
}
|
||||||
|
for name, call := range tests {
|
||||||
|
t.Run(name, func(t *testing.T) {
|
||||||
|
var b escpos.Builder
|
||||||
|
if err := call(&b); !errors.Is(err, escpos.ErrInvalidArgument) || b.Len() != 0 {
|
||||||
|
t.Errorf("err=%v len=%d, want ErrInvalidArgument and nothing written", err, b.Len())
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEncodeCodePage437(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
in string
|
||||||
|
want []byte
|
||||||
|
}{
|
||||||
|
{"ascii", "Hello, World!", []byte("Hello, World!")},
|
||||||
|
{"box drawing", "┌─┐│└┘", []byte{0xDA, 0xC4, 0xBF, 0xB3, 0xC0, 0xD9}},
|
||||||
|
{"shading", "░▒▓█", []byte{0xB0, 0xB1, 0xB2, 0xDB}},
|
||||||
|
{"double box", "╔═╗", []byte{0xC9, 0xCD, 0xBB}},
|
||||||
|
{"umlauts", "Über ä ö", []byte{0x9A, 'b', 'e', 'r', ' ', 0x84, ' ', 0x94}},
|
||||||
|
{"symbols", "£°±", []byte{0x9C, 0xF8, 0xF1}},
|
||||||
|
{"unmappable emoji", "hi 🎉", []byte("hi ?")},
|
||||||
|
{"keeps newline and tab", "a\nb\tc", []byte("a\nb\tc")},
|
||||||
|
// ESC is dropped, so the '@' that followed it is harmless text.
|
||||||
|
{"drops control characters", "a\x1b@b\x00c\r", []byte("a@bc")},
|
||||||
|
{"smiley maps below 0x20 so becomes ?", "☺", []byte("?")},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
got := escpos.CodePage437.Encode(tt.in)
|
||||||
|
if !bytes.Equal(got, tt.want) {
|
||||||
|
t.Errorf("Encode(%q) = % X, want % X", tt.in, got, tt.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEncodeOtherCodePages(t *testing.T) {
|
||||||
|
if got := escpos.CodePage858.Encode("€"); !bytes.Equal(got, []byte{0xD5}) {
|
||||||
|
t.Errorf("cp858 € = % X, want D5", got)
|
||||||
|
}
|
||||||
|
if got := escpos.CodePage1252.Encode("ێ"); !bytes.Equal(got, []byte{0x80, 0xE9}) {
|
||||||
|
t.Errorf("cp1252 ێ = % X, want 80 E9", got)
|
||||||
|
}
|
||||||
|
if got := escpos.CodePage850.Encode("é"); !bytes.Equal(got, []byte{0x82}) {
|
||||||
|
t.Errorf("cp850 é = % X, want 82", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestParseCodePage(t *testing.T) {
|
||||||
|
for _, name := range []string{"cp437", "CP437", "437"} {
|
||||||
|
if cp, err := escpos.ParseCodePage(name); err != nil || cp != escpos.CodePage437 {
|
||||||
|
t.Errorf("ParseCodePage(%q) = %v, %v", name, cp, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, err := escpos.ParseCodePage("ebcdic"); !errors.Is(err, escpos.ErrInvalidArgument) {
|
||||||
|
t.Errorf("ParseCodePage(ebcdic) err = %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRasterImagePacksBitsAndPadsWidth(t *testing.T) {
|
||||||
|
// 10x2 image: row 0 is black at x=0 and x=9, row 1 is all white.
|
||||||
|
img := image.NewGray(image.Rect(0, 0, 10, 2))
|
||||||
|
for i := range img.Pix {
|
||||||
|
img.Pix[i] = 0xFF
|
||||||
|
}
|
||||||
|
img.SetGray(0, 0, color.Gray{})
|
||||||
|
img.SetGray(9, 0, color.Gray{})
|
||||||
|
|
||||||
|
var b escpos.Builder
|
||||||
|
if err := b.RasterImage(img); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
want := []byte{
|
||||||
|
0x1D, 0x76, 0x30, 0, 2, 0, 2, 0, // 2 bytes wide, 2 rows
|
||||||
|
0x80, 0x40, // row 0: bit for x=0, bit for x=9
|
||||||
|
0x00, 0x00, // row 1: padding stays white
|
||||||
|
}
|
||||||
|
if !bytes.Equal(b.Bytes(), want) {
|
||||||
|
t.Errorf("got % X, want % X", b.Bytes(), want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRasterImageRespectsBoundsOrigin(t *testing.T) {
|
||||||
|
// A sub-image whose bounds do not start at (0,0).
|
||||||
|
full := image.NewGray(image.Rect(0, 0, 16, 4))
|
||||||
|
for i := range full.Pix {
|
||||||
|
full.Pix[i] = 0xFF
|
||||||
|
}
|
||||||
|
full.SetGray(8, 2, color.Gray{})
|
||||||
|
sub := full.SubImage(image.Rect(8, 2, 16, 3))
|
||||||
|
|
||||||
|
var b escpos.Builder
|
||||||
|
if err := b.RasterImage(sub); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
want := []byte{0x1D, 0x76, 0x30, 0, 1, 0, 1, 0, 0x80}
|
||||||
|
if !bytes.Equal(b.Bytes(), want) {
|
||||||
|
t.Errorf("got % X, want % X", b.Bytes(), want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRasterImageBandsTallImages(t *testing.T) {
|
||||||
|
img := image.NewGray(image.Rect(0, 0, 8, 600))
|
||||||
|
var b escpos.Builder
|
||||||
|
if err := b.RasterImage(img); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
headers := []([]byte){
|
||||||
|
{0x1D, 0x76, 0x30, 0, 1, 0, 0x00, 0x01}, // 256 rows
|
||||||
|
{0x1D, 0x76, 0x30, 0, 1, 0, 0x00, 0x01}, // 256 rows
|
||||||
|
{0x1D, 0x76, 0x30, 0, 1, 0, 88, 0}, // 88 rows
|
||||||
|
}
|
||||||
|
out := b.Bytes()
|
||||||
|
for i, h := range headers {
|
||||||
|
if !bytes.HasPrefix(out, h) {
|
||||||
|
t.Fatalf("band %d header = % X, want % X", i, out[:min(8, len(out))], h)
|
||||||
|
}
|
||||||
|
rows := int(h[6]) | int(h[7])<<8
|
||||||
|
out = out[8+rows:]
|
||||||
|
}
|
||||||
|
if len(out) != 0 {
|
||||||
|
t.Errorf("%d trailing bytes", len(out))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRasterImageTransparentIsWhite(t *testing.T) {
|
||||||
|
img := image.NewNRGBA(image.Rect(0, 0, 8, 1))
|
||||||
|
img.SetNRGBA(0, 0, color.NRGBA{A: 0}) // transparent black: paper shows
|
||||||
|
img.SetNRGBA(1, 0, color.NRGBA{A: 255}) // opaque black
|
||||||
|
img.SetNRGBA(2, 0, color.NRGBA{R: 255, G: 255, B: 255, A: 255})
|
||||||
|
var b escpos.Builder
|
||||||
|
if err := b.RasterImage(img); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if got := b.Bytes()[8]; got != 0x40 {
|
||||||
|
t.Errorf("row byte = %08b, want 01000000", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRasterImageEmpty(t *testing.T) {
|
||||||
|
var b escpos.Builder
|
||||||
|
if err := b.RasterImage(image.NewGray(image.Rect(0, 0, 0, 0))); !errors.Is(err, escpos.ErrInvalidArgument) {
|
||||||
|
t.Errorf("err = %v, want ErrInvalidArgument", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestStatusApply(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
resps map[escpos.StatusKind]byte
|
||||||
|
want escpos.Status
|
||||||
|
ready bool
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "healthy",
|
||||||
|
resps: map[escpos.StatusKind]byte{1: 0x12, 2: 0x12, 3: 0x12, 4: 0x12},
|
||||||
|
want: escpos.Status{Online: true},
|
||||||
|
ready: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "cover open",
|
||||||
|
resps: map[escpos.StatusKind]byte{1: 0x1A, 2: 0x16, 3: 0x12, 4: 0x12},
|
||||||
|
want: escpos.Status{CoverOpen: true},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "paper near end",
|
||||||
|
resps: map[escpos.StatusKind]byte{1: 0x12, 2: 0x12, 3: 0x12, 4: 0x1E},
|
||||||
|
want: escpos.Status{Online: true, PaperNearEnd: true},
|
||||||
|
ready: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "paper out",
|
||||||
|
resps: map[escpos.StatusKind]byte{1: 0x1A, 2: 0x32, 3: 0x12, 4: 0x72},
|
||||||
|
want: escpos.Status{PaperOut: true},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "cutter error",
|
||||||
|
resps: map[escpos.StatusKind]byte{1: 0x1A, 2: 0x52, 3: 0x1A, 4: 0x12},
|
||||||
|
want: escpos.Status{CutterError: true},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
var s escpos.Status
|
||||||
|
for _, kind := range escpos.StatusKinds() {
|
||||||
|
if err := s.Apply(kind, tt.resps[kind]); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if s != tt.want {
|
||||||
|
t.Errorf("status = %+v, want %+v", s, tt.want)
|
||||||
|
}
|
||||||
|
if s.Ready() != tt.ready {
|
||||||
|
t.Errorf("Ready() = %v, want %v", s.Ready(), tt.ready)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestStatusApplyRejectsGarbage(t *testing.T) {
|
||||||
|
var s escpos.Status
|
||||||
|
if err := s.Apply(escpos.StatusPrinter, 'H'); !errors.Is(err, escpos.ErrInvalidArgument) {
|
||||||
|
t.Errorf("err = %v, want ErrInvalidArgument", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestStatusRequest(t *testing.T) {
|
||||||
|
if got := escpos.StatusRequest(escpos.StatusPaper); !bytes.Equal(got, []byte{0x10, 0x04, 4}) {
|
||||||
|
t.Errorf("got % X", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLookupProfile(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
model string
|
||||||
|
wantName string
|
||||||
|
colsA, colsB int
|
||||||
|
}{
|
||||||
|
{"tm-t20ii", "tm-t20", 48, 64},
|
||||||
|
{"TM-T88V", "tm-t88", 42, 56},
|
||||||
|
{"generic-58mm", "generic-58mm", 32, 42},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
p, err := escpos.LookupProfile(tt.model)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("LookupProfile(%q): %v", tt.model, err)
|
||||||
|
}
|
||||||
|
if p.Name != tt.wantName || p.Columns(escpos.FontA) != tt.colsA || p.Columns(escpos.FontB) != tt.colsB {
|
||||||
|
t.Errorf("%q: name=%s cols=%d/%d, want %s %d/%d", tt.model, p.Name,
|
||||||
|
p.Columns(escpos.FontA), p.Columns(escpos.FontB), tt.wantName, tt.colsA, tt.colsB)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, err := escpos.LookupProfile("sol-802"); !errors.Is(err, escpos.ErrInvalidArgument) {
|
||||||
|
t.Errorf("unknown model err = %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
package escpos
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Profile describes the printable area and fonts of a printer model.
|
||||||
|
type Profile struct {
|
||||||
|
// Name is the canonical model name.
|
||||||
|
Name string
|
||||||
|
|
||||||
|
// DotsPerLine is the printable width in dots.
|
||||||
|
DotsPerLine int
|
||||||
|
|
||||||
|
// FontAWidth and FontBWidth are the glyph widths in dots, including
|
||||||
|
// default character spacing, at scale 1.
|
||||||
|
FontAWidth int
|
||||||
|
FontBWidth int
|
||||||
|
}
|
||||||
|
|
||||||
|
// LookupProfile returns the profile for a model name such as "tm-t20". Common
|
||||||
|
// model variants (e.g. "tm-t20ii") resolve to their family.
|
||||||
|
func LookupProfile(model string) (Profile, error) {
|
||||||
|
switch strings.ToLower(strings.TrimSpace(model)) {
|
||||||
|
case "tm-t20", "tm-t20ii", "tm-t20iii", "tm-t20iv":
|
||||||
|
// 80 mm paper at 203 dpi: 48 columns of Font A, 64 of Font B.
|
||||||
|
return Profile{Name: "tm-t20", DotsPerLine: 576, FontAWidth: 12, FontBWidth: 9}, nil
|
||||||
|
case "tm-t88", "tm-t88iv", "tm-t88v", "tm-t88vi", "tm-t88vii":
|
||||||
|
// 80 mm paper at 180 dpi: 42 columns of Font A, 56 of Font B.
|
||||||
|
return Profile{Name: "tm-t88", DotsPerLine: 512, FontAWidth: 12, FontBWidth: 9}, nil
|
||||||
|
case "generic-80mm":
|
||||||
|
return Profile{Name: "generic-80mm", DotsPerLine: 576, FontAWidth: 12, FontBWidth: 9}, nil
|
||||||
|
case "generic-58mm":
|
||||||
|
// 58 mm paper at 203 dpi: 32 columns of Font A.
|
||||||
|
return Profile{Name: "generic-58mm", DotsPerLine: 384, FontAWidth: 12, FontBWidth: 9}, nil
|
||||||
|
}
|
||||||
|
return Profile{}, fmt.Errorf("%w: unknown printer model %q (want tm-t20, tm-t88, generic-80mm or generic-58mm)",
|
||||||
|
ErrInvalidArgument, model)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GlyphWidth returns the width in dots of one character in font f at scale 1.
|
||||||
|
func (p Profile) GlyphWidth(f Font) int {
|
||||||
|
if f == FontB {
|
||||||
|
return p.FontBWidth
|
||||||
|
}
|
||||||
|
return p.FontAWidth
|
||||||
|
}
|
||||||
|
|
||||||
|
// Columns returns how many characters of font f at scale 1 fit on a line.
|
||||||
|
func (p Profile) Columns(f Font) int {
|
||||||
|
return p.DotsPerLine / p.GlyphWidth(f)
|
||||||
|
}
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
package escpos
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// QRCorrection is the QR code error correction level. Higher levels survive
|
||||||
|
// more damage at the cost of a denser code.
|
||||||
|
type QRCorrection byte
|
||||||
|
|
||||||
|
// QRCorrection values for GS ( k function 169.
|
||||||
|
const (
|
||||||
|
QRCorrectionL QRCorrection = 48 // about 7% recovery
|
||||||
|
QRCorrectionM QRCorrection = 49 // about 15% recovery
|
||||||
|
QRCorrectionQ QRCorrection = 50 // about 25% recovery
|
||||||
|
QRCorrectionH QRCorrection = 51 // about 30% recovery
|
||||||
|
)
|
||||||
|
|
||||||
|
// QR code limits.
|
||||||
|
const (
|
||||||
|
MaxQRData = 7089 // bytes the printer's symbol storage accepts
|
||||||
|
MinQRModuleSize = 1
|
||||||
|
MaxQRModuleSize = 16
|
||||||
|
)
|
||||||
|
|
||||||
|
// ParseQRCorrection returns the correction level named by name: L, M, Q or H.
|
||||||
|
func ParseQRCorrection(name string) (QRCorrection, error) {
|
||||||
|
switch strings.ToUpper(strings.TrimSpace(name)) {
|
||||||
|
case "L":
|
||||||
|
return QRCorrectionL, nil
|
||||||
|
case "M":
|
||||||
|
return QRCorrectionM, nil
|
||||||
|
case "Q":
|
||||||
|
return QRCorrectionQ, nil
|
||||||
|
case "H":
|
||||||
|
return QRCorrectionH, nil
|
||||||
|
}
|
||||||
|
return 0, fmt.Errorf("%w: unknown QR correction level %q (want L, M, Q or H)", ErrInvalidArgument, name)
|
||||||
|
}
|
||||||
|
|
||||||
|
// QRCode appends a model 2 QR code holding data, printed with square modules
|
||||||
|
// moduleSize dots wide.
|
||||||
|
func (b *Builder) QRCode(data []byte, moduleSize int, level QRCorrection) error {
|
||||||
|
switch {
|
||||||
|
case len(data) == 0:
|
||||||
|
return fmt.Errorf("%w: QR data is empty", ErrInvalidArgument)
|
||||||
|
case len(data) > MaxQRData:
|
||||||
|
return fmt.Errorf("%w: QR data is %d bytes, limit is %d", ErrInvalidArgument, len(data), MaxQRData)
|
||||||
|
case moduleSize < MinQRModuleSize || moduleSize > MaxQRModuleSize:
|
||||||
|
return fmt.Errorf("%w: QR module size %d must be within %d-%d",
|
||||||
|
ErrInvalidArgument, moduleSize, MinQRModuleSize, MaxQRModuleSize)
|
||||||
|
case level < QRCorrectionL || level > QRCorrectionH:
|
||||||
|
return fmt.Errorf("%w: unknown QR correction level %d", ErrInvalidArgument, byte(level))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Function 165: select model 2.
|
||||||
|
b.buf.Write([]byte{gs, '(', 'k', 4, 0, '1', 'A', '2', 0})
|
||||||
|
// Function 167: module size.
|
||||||
|
b.buf.Write([]byte{gs, '(', 'k', 3, 0, '1', 'C', byte(moduleSize)})
|
||||||
|
// Function 169: error correction level.
|
||||||
|
b.buf.Write([]byte{gs, '(', 'k', 3, 0, '1', 'E', byte(level)})
|
||||||
|
// Function 180: store data. The length covers cn, fn, m and the data.
|
||||||
|
n := len(data) + 3
|
||||||
|
b.buf.Write([]byte{gs, '(', 'k', byte(n), byte(n >> 8), '1', 'P', '0'})
|
||||||
|
b.buf.Write(data)
|
||||||
|
// Function 181: print the stored symbol.
|
||||||
|
b.buf.Write([]byte{gs, '(', 'k', 3, 0, '1', 'Q', '0'})
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
package escpos
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"image"
|
||||||
|
"image/color"
|
||||||
|
)
|
||||||
|
|
||||||
|
// rasterBandHeight is the number of rows sent per GS v 0 command. Splitting
|
||||||
|
// tall images keeps every command within the height limits of all supported
|
||||||
|
// models (TM-T20 accepts up to 2303 rows).
|
||||||
|
const rasterBandHeight = 256
|
||||||
|
|
||||||
|
// maxRasterWidthBytes bounds the image width so xL/xH stay meaningful.
|
||||||
|
const maxRasterWidthBytes = 0xFFFF
|
||||||
|
|
||||||
|
// RasterImage appends img as one or more GS v 0 raster bit images. Pixels
|
||||||
|
// darker than 50% luminance, after compositing onto white paper, print black.
|
||||||
|
// Dither images first (see the raster package) for photographic content. The
|
||||||
|
// width is padded with white up to a multiple of 8 dots.
|
||||||
|
func (b *Builder) RasterImage(img image.Image) error {
|
||||||
|
bounds := img.Bounds()
|
||||||
|
width, height := bounds.Dx(), bounds.Dy()
|
||||||
|
if width <= 0 || height <= 0 {
|
||||||
|
return fmt.Errorf("%w: image is empty", ErrInvalidArgument)
|
||||||
|
}
|
||||||
|
widthBytes := (width + 7) / 8
|
||||||
|
if widthBytes > maxRasterWidthBytes {
|
||||||
|
return fmt.Errorf("%w: image is %d dots wide", ErrInvalidArgument, width)
|
||||||
|
}
|
||||||
|
|
||||||
|
dark := darkFunc(img)
|
||||||
|
row := make([]byte, widthBytes)
|
||||||
|
for top := 0; top < height; top += rasterBandHeight {
|
||||||
|
rows := min(rasterBandHeight, height-top)
|
||||||
|
b.buf.Write([]byte{gs, 'v', '0', 0,
|
||||||
|
byte(widthBytes), byte(widthBytes >> 8),
|
||||||
|
byte(rows), byte(rows >> 8)})
|
||||||
|
for y := top; y < top+rows; y++ {
|
||||||
|
clear(row)
|
||||||
|
for x := range width {
|
||||||
|
if dark(bounds.Min.X+x, bounds.Min.Y+y) {
|
||||||
|
row[x/8] |= 0x80 >> (x % 8)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
b.buf.Write(row)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// darkFunc returns a pixel test for img, with fast paths for the image types
|
||||||
|
// the raster package produces.
|
||||||
|
func darkFunc(img image.Image) func(x, y int) bool {
|
||||||
|
switch m := img.(type) {
|
||||||
|
case *image.Paletted:
|
||||||
|
dark := make([]bool, len(m.Palette))
|
||||||
|
for i, c := range m.Palette {
|
||||||
|
dark[i] = isDark(c)
|
||||||
|
}
|
||||||
|
return func(x, y int) bool {
|
||||||
|
idx := m.ColorIndexAt(x, y)
|
||||||
|
return int(idx) < len(dark) && dark[idx]
|
||||||
|
}
|
||||||
|
case *image.Gray:
|
||||||
|
return func(x, y int) bool {
|
||||||
|
return m.GrayAt(x, y).Y < 0x80
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return func(x, y int) bool {
|
||||||
|
return isDark(img.At(x, y))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// isDark composites c onto white and reports whether its luminance is below
|
||||||
|
// 50%. RGBA returns alpha-premultiplied values, so adding the uncovered
|
||||||
|
// fraction of white is enough to composite.
|
||||||
|
func isDark(c color.Color) bool {
|
||||||
|
r, g, bl, a := c.RGBA()
|
||||||
|
white := 0xFFFF - a
|
||||||
|
luma := (299*(r+white) + 587*(g+white) + 114*(bl+white)) / 1000
|
||||||
|
return luma < 0x8000
|
||||||
|
}
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
package escpos
|
||||||
|
|
||||||
|
import "fmt"
|
||||||
|
|
||||||
|
// StatusKind selects which real-time status byte DLE EOT requests.
|
||||||
|
type StatusKind byte
|
||||||
|
|
||||||
|
// StatusKind values for DLE EOT n.
|
||||||
|
const (
|
||||||
|
StatusPrinter StatusKind = 1
|
||||||
|
StatusOffline StatusKind = 2
|
||||||
|
StatusError StatusKind = 3
|
||||||
|
StatusPaper StatusKind = 4
|
||||||
|
)
|
||||||
|
|
||||||
|
// StatusKinds lists every status kind in the order a full query sends them.
|
||||||
|
func StatusKinds() []StatusKind {
|
||||||
|
return []StatusKind{StatusPrinter, StatusOffline, StatusError, StatusPaper}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Status is the printer state decoded from DLE EOT responses.
|
||||||
|
type Status struct {
|
||||||
|
Online bool
|
||||||
|
CoverOpen bool
|
||||||
|
PaperNearEnd bool
|
||||||
|
PaperOut bool
|
||||||
|
CutterError bool
|
||||||
|
Unrecoverable bool
|
||||||
|
// AutoRecoverable reports an error the printer clears by itself, such as
|
||||||
|
// a print head that is too hot.
|
||||||
|
AutoRecoverable bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ready reports whether the printer can print right now.
|
||||||
|
func (s Status) Ready() bool {
|
||||||
|
return s.Online && !s.CoverOpen && !s.PaperOut && !s.CutterError && !s.Unrecoverable && !s.AutoRecoverable
|
||||||
|
}
|
||||||
|
|
||||||
|
// StatusRequest returns the real-time DLE EOT n command for kind. Real-time
|
||||||
|
// commands are executed immediately, even while the printer is busy.
|
||||||
|
func StatusRequest(kind StatusKind) []byte {
|
||||||
|
return []byte{dle, eot, byte(kind)}
|
||||||
|
}
|
||||||
|
|
||||||
|
// statusFixedMask and statusFixedBits describe the bits every DLE EOT
|
||||||
|
// response has fixed: bits 0 and 7 are 0, bits 1 and 4 are 1.
|
||||||
|
const (
|
||||||
|
statusFixedMask byte = 0x93
|
||||||
|
statusFixedBits byte = 0x12
|
||||||
|
)
|
||||||
|
|
||||||
|
// Apply decodes resp, the printer's answer to StatusRequest(kind), into s.
|
||||||
|
func (s *Status) Apply(kind StatusKind, resp byte) error {
|
||||||
|
if resp&statusFixedMask != statusFixedBits {
|
||||||
|
return fmt.Errorf("%w: 0x%02X is not a DLE EOT %d response", ErrInvalidArgument, resp, kind)
|
||||||
|
}
|
||||||
|
bit := func(n uint) bool { return resp&(1<<n) != 0 }
|
||||||
|
switch kind {
|
||||||
|
case StatusPrinter:
|
||||||
|
s.Online = !bit(3)
|
||||||
|
case StatusOffline:
|
||||||
|
s.CoverOpen = bit(2)
|
||||||
|
s.PaperOut = s.PaperOut || bit(5)
|
||||||
|
case StatusError:
|
||||||
|
s.CutterError = bit(3)
|
||||||
|
s.Unrecoverable = bit(5)
|
||||||
|
s.AutoRecoverable = bit(6)
|
||||||
|
case StatusPaper:
|
||||||
|
s.PaperNearEnd = bit(2) && bit(3)
|
||||||
|
s.PaperOut = s.PaperOut || (bit(5) && bit(6))
|
||||||
|
default:
|
||||||
|
return fmt.Errorf("%w: unknown status kind %d", ErrInvalidArgument, kind)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
// Package printer talks to a network receipt printer over a raw TCP socket
|
||||||
|
// (the "port 9100" / JetDirect protocol).
|
||||||
|
package printer
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/escpos"
|
||||||
|
)
|
||||||
|
|
||||||
|
// statusTimeout bounds how long the printer may take to answer one real-time
|
||||||
|
// status request.
|
||||||
|
const statusTimeout = 2 * time.Second
|
||||||
|
|
||||||
|
// ErrStatusUnsupported is returned by Status when the printer accepts the
|
||||||
|
// connection but does not answer DLE EOT requests.
|
||||||
|
var ErrStatusUnsupported = errors.New("printer: no answer to status request")
|
||||||
|
|
||||||
|
// Client sends data to one printer. Network printers accept a single
|
||||||
|
// connection at a time, so the Client serialises its connections. It is safe
|
||||||
|
// for concurrent use.
|
||||||
|
type Client struct {
|
||||||
|
addr string
|
||||||
|
dialTimeout time.Duration
|
||||||
|
writeTimeout time.Duration
|
||||||
|
dialer net.Dialer
|
||||||
|
|
||||||
|
// slot holds a token while a connection is open; acquiring it respects
|
||||||
|
// context cancellation, unlike a mutex.
|
||||||
|
slot chan struct{}
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewClient returns a Client for the printer at addr ("host:port").
|
||||||
|
func NewClient(addr string, dialTimeout, writeTimeout time.Duration) *Client {
|
||||||
|
if addr == "" {
|
||||||
|
panic("printer.NewClient: addr must not be empty")
|
||||||
|
}
|
||||||
|
if dialTimeout <= 0 || writeTimeout <= 0 {
|
||||||
|
panic("printer.NewClient: timeouts must be positive")
|
||||||
|
}
|
||||||
|
return &Client{
|
||||||
|
addr: addr,
|
||||||
|
dialTimeout: dialTimeout,
|
||||||
|
writeTimeout: writeTimeout,
|
||||||
|
dialer: net.Dialer{Timeout: dialTimeout},
|
||||||
|
slot: make(chan struct{}, 1),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Addr returns the printer address.
|
||||||
|
func (c *Client) Addr() string {
|
||||||
|
return c.addr
|
||||||
|
}
|
||||||
|
|
||||||
|
// Send writes data to the printer in one connection.
|
||||||
|
func (c *Client) Send(ctx context.Context, data []byte) error {
|
||||||
|
conn, release, err := c.connect(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer release()
|
||||||
|
|
||||||
|
if err := conn.SetWriteDeadline(c.deadline(ctx, c.writeTimeout)); err != nil {
|
||||||
|
return fmt.Errorf("setting printer write deadline: %w", err)
|
||||||
|
}
|
||||||
|
if _, err := conn.Write(data); err != nil {
|
||||||
|
return fmt.Errorf("writing to printer %s: %w", c.addr, err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Status queries the printer's real-time status. It returns
|
||||||
|
// ErrStatusUnsupported when the printer is reachable but does not answer.
|
||||||
|
func (c *Client) Status(ctx context.Context) (escpos.Status, error) {
|
||||||
|
var status escpos.Status
|
||||||
|
conn, release, err := c.connect(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return status, err
|
||||||
|
}
|
||||||
|
defer release()
|
||||||
|
|
||||||
|
resp := make([]byte, 1)
|
||||||
|
for _, kind := range escpos.StatusKinds() {
|
||||||
|
deadline := c.deadline(ctx, statusTimeout)
|
||||||
|
if err := conn.SetDeadline(deadline); err != nil {
|
||||||
|
return status, fmt.Errorf("setting printer deadline: %w", err)
|
||||||
|
}
|
||||||
|
if _, err := conn.Write(escpos.StatusRequest(kind)); err != nil {
|
||||||
|
return status, fmt.Errorf("requesting printer status: %w", err)
|
||||||
|
}
|
||||||
|
if _, err := conn.Read(resp); err != nil {
|
||||||
|
var netErr net.Error
|
||||||
|
if errors.As(err, &netErr) && netErr.Timeout() {
|
||||||
|
return status, ErrStatusUnsupported
|
||||||
|
}
|
||||||
|
return status, fmt.Errorf("reading printer status: %w", err)
|
||||||
|
}
|
||||||
|
if err := status.Apply(kind, resp[0]); err != nil {
|
||||||
|
return status, ErrStatusUnsupported
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return status, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// connect waits for the connection slot and dials the printer. The returned
|
||||||
|
// release func closes the connection and frees the slot.
|
||||||
|
func (c *Client) connect(ctx context.Context) (net.Conn, func(), error) {
|
||||||
|
select {
|
||||||
|
case c.slot <- struct{}{}:
|
||||||
|
case <-ctx.Done():
|
||||||
|
return nil, nil, fmt.Errorf("waiting for printer %s: %w", c.addr, ctx.Err())
|
||||||
|
}
|
||||||
|
conn, err := c.dialer.DialContext(ctx, "tcp", c.addr)
|
||||||
|
if err != nil {
|
||||||
|
<-c.slot
|
||||||
|
return nil, nil, fmt.Errorf("connecting to printer %s: %w", c.addr, err)
|
||||||
|
}
|
||||||
|
release := func() {
|
||||||
|
// Close errors after a completed write carry no information the
|
||||||
|
// caller can act on: the data has already been handed to the OS.
|
||||||
|
_ = conn.Close()
|
||||||
|
<-c.slot
|
||||||
|
}
|
||||||
|
return conn, release, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// deadline returns now+d, or the context deadline if that is sooner.
|
||||||
|
func (c *Client) deadline(ctx context.Context, d time.Duration) time.Time {
|
||||||
|
deadline := time.Now().Add(d)
|
||||||
|
if ctxDeadline, ok := ctx.Deadline(); ok && ctxDeadline.Before(deadline) {
|
||||||
|
return ctxDeadline
|
||||||
|
}
|
||||||
|
return deadline
|
||||||
|
}
|
||||||
@@ -0,0 +1,128 @@
|
|||||||
|
package printer_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"net"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/escpos"
|
||||||
|
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/printer"
|
||||||
|
)
|
||||||
|
|
||||||
|
// fakePrinter accepts one connection per handle call.
|
||||||
|
func fakePrinter(t *testing.T, handle func(net.Conn)) string {
|
||||||
|
t.Helper()
|
||||||
|
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { _ = ln.Close() })
|
||||||
|
go func() {
|
||||||
|
for {
|
||||||
|
conn, err := ln.Accept()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
go func() {
|
||||||
|
defer conn.Close()
|
||||||
|
handle(conn)
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
return ln.Addr().String()
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSend(t *testing.T) {
|
||||||
|
received := make(chan []byte, 1)
|
||||||
|
addr := fakePrinter(t, func(conn net.Conn) {
|
||||||
|
data, _ := io.ReadAll(conn)
|
||||||
|
received <- data
|
||||||
|
})
|
||||||
|
client := printer.NewClient(addr, time.Second, time.Second)
|
||||||
|
if err := client.Send(context.Background(), []byte("receipt")); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
select {
|
||||||
|
case got := <-received:
|
||||||
|
if !bytes.Equal(got, []byte("receipt")) {
|
||||||
|
t.Errorf("printer got %q", got)
|
||||||
|
}
|
||||||
|
case <-time.After(2 * time.Second):
|
||||||
|
t.Fatal("printer received nothing")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSendUnreachable(t *testing.T) {
|
||||||
|
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
addr := ln.Addr().String()
|
||||||
|
_ = ln.Close() // nothing listens here now
|
||||||
|
|
||||||
|
client := printer.NewClient(addr, 500*time.Millisecond, time.Second)
|
||||||
|
if err := client.Send(context.Background(), []byte("x")); err == nil {
|
||||||
|
t.Fatal("expected a connection error")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSendRespectsCancelledContextWhileBusy(t *testing.T) {
|
||||||
|
release := make(chan struct{})
|
||||||
|
addr := fakePrinter(t, func(conn net.Conn) {
|
||||||
|
<-release
|
||||||
|
_, _ = io.Copy(io.Discard, conn)
|
||||||
|
})
|
||||||
|
t.Cleanup(func() { close(release) })
|
||||||
|
client := printer.NewClient(addr, time.Second, 5*time.Second)
|
||||||
|
|
||||||
|
// Hold the single connection slot with a status query that never gets
|
||||||
|
// an answer, then try to send with a short deadline.
|
||||||
|
go func() { _, _ = client.Status(context.Background()) }()
|
||||||
|
time.Sleep(100 * time.Millisecond)
|
||||||
|
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
|
||||||
|
defer cancel()
|
||||||
|
if err := client.Send(ctx, []byte("x")); !errors.Is(err, context.DeadlineExceeded) {
|
||||||
|
t.Errorf("err = %v, want context.DeadlineExceeded", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestStatus(t *testing.T) {
|
||||||
|
answers := map[byte]byte{1: 0x12, 2: 0x12, 3: 0x12, 4: 0x1E} // paper near end
|
||||||
|
addr := fakePrinter(t, func(conn net.Conn) {
|
||||||
|
req := make([]byte, 3)
|
||||||
|
for {
|
||||||
|
if _, err := io.ReadFull(conn, req); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if req[0] != 0x10 || req[1] != 0x04 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
_, _ = conn.Write([]byte{answers[req[2]]})
|
||||||
|
}
|
||||||
|
})
|
||||||
|
client := printer.NewClient(addr, time.Second, time.Second)
|
||||||
|
status, err := client.Status(context.Background())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if want := (escpos.Status{Online: true, PaperNearEnd: true}); status != want {
|
||||||
|
t.Errorf("status = %+v, want %+v", status, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestStatusUnsupported(t *testing.T) {
|
||||||
|
addr := fakePrinter(t, func(conn net.Conn) {
|
||||||
|
_, _ = io.Copy(io.Discard, conn) // a printer that never answers
|
||||||
|
})
|
||||||
|
client := printer.NewClient(addr, time.Second, time.Second)
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond)
|
||||||
|
defer cancel()
|
||||||
|
if _, err := client.Status(ctx); !errors.Is(err, printer.ErrStatusUnsupported) {
|
||||||
|
t.Errorf("err = %v, want ErrStatusUnsupported", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,294 @@
|
|||||||
|
// Package printqueue prints jobs one at a time, in submission order, and
|
||||||
|
// keeps track of their status.
|
||||||
|
package printqueue
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"log/slog"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"go.jetify.com/typeid"
|
||||||
|
|
||||||
|
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/receipt"
|
||||||
|
)
|
||||||
|
|
||||||
|
// jobTimeout bounds rendering and sending one job, including retries.
|
||||||
|
const jobTimeout = 2 * time.Minute
|
||||||
|
|
||||||
|
var (
|
||||||
|
// ErrQueueFull is returned by Submit when no more jobs can wait.
|
||||||
|
ErrQueueFull = errors.New("print queue is full")
|
||||||
|
|
||||||
|
// ErrClosed is returned by Submit once the queue has shut down.
|
||||||
|
ErrClosed = errors.New("print queue is shut down")
|
||||||
|
|
||||||
|
// ErrNotFound is returned by Status for unknown or expired job IDs.
|
||||||
|
ErrNotFound = errors.New("job not found")
|
||||||
|
|
||||||
|
errShuttingDown = errors.New("server shutting down before the job was printed")
|
||||||
|
)
|
||||||
|
|
||||||
|
// jobPrefix gives job IDs their "job_" prefix.
|
||||||
|
type jobPrefix struct{}
|
||||||
|
|
||||||
|
// Prefix implements typeid.PrefixType.
|
||||||
|
func (jobPrefix) Prefix() string { return "job" }
|
||||||
|
|
||||||
|
// JobID identifies a print job, e.g. "job_01h455vb4pex5vsknk084sn02q". It is
|
||||||
|
// a TypeID: a UUIDv7, so IDs sort by creation time.
|
||||||
|
type JobID struct {
|
||||||
|
typeid.TypeID[jobPrefix]
|
||||||
|
}
|
||||||
|
|
||||||
|
// ParseJobID parses s as a JobID.
|
||||||
|
func ParseJobID(s string) (JobID, error) {
|
||||||
|
return typeid.Parse[JobID](s)
|
||||||
|
}
|
||||||
|
|
||||||
|
// State is a job's position in its lifecycle.
|
||||||
|
type State string
|
||||||
|
|
||||||
|
// Job states.
|
||||||
|
const (
|
||||||
|
StateQueued State = "queued"
|
||||||
|
StatePrinting State = "printing"
|
||||||
|
StateDone State = "done"
|
||||||
|
StateFailed State = "failed"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Status describes a job.
|
||||||
|
type Status struct {
|
||||||
|
ID JobID `json:"id"`
|
||||||
|
State State `json:"status"`
|
||||||
|
Error string `json:"error,omitempty"`
|
||||||
|
Attempts int `json:"attempts,omitempty"`
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
StartedAt *time.Time `json:"started_at,omitempty"`
|
||||||
|
FinishedAt *time.Time `json:"finished_at,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Renderer turns a job into printer bytes.
|
||||||
|
type Renderer interface {
|
||||||
|
Render(ctx context.Context, job receipt.Job) ([]byte, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sender delivers bytes to the printer.
|
||||||
|
type Sender interface {
|
||||||
|
Send(ctx context.Context, data []byte) error
|
||||||
|
}
|
||||||
|
|
||||||
|
// Options configures a Queue.
|
||||||
|
type Options struct {
|
||||||
|
// Size is how many jobs may wait.
|
||||||
|
Size int
|
||||||
|
|
||||||
|
// History is how many finished jobs keep their status.
|
||||||
|
History int
|
||||||
|
|
||||||
|
// Retries is how many times a failed send is retried; RetryDelay is the
|
||||||
|
// first wait, doubling after each attempt.
|
||||||
|
Retries int
|
||||||
|
RetryDelay time.Duration
|
||||||
|
|
||||||
|
// OnFailure, if set, is called for every job that fails, e.g. to report
|
||||||
|
// it to an error tracker.
|
||||||
|
OnFailure func(id JobID, err error)
|
||||||
|
}
|
||||||
|
|
||||||
|
type queuedJob struct {
|
||||||
|
id JobID
|
||||||
|
job receipt.Job
|
||||||
|
}
|
||||||
|
|
||||||
|
// Queue runs print jobs on a single worker. It is safe for concurrent use.
|
||||||
|
type Queue struct {
|
||||||
|
renderer Renderer
|
||||||
|
sender Sender
|
||||||
|
logger *slog.Logger
|
||||||
|
options Options
|
||||||
|
jobs chan queuedJob
|
||||||
|
|
||||||
|
// mu guards statuses, finished and closed.
|
||||||
|
mu sync.Mutex
|
||||||
|
statuses map[JobID]*Status
|
||||||
|
finished []JobID // oldest first, for history eviction
|
||||||
|
closed bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// New returns a Queue. Call Run to start printing.
|
||||||
|
func New(renderer Renderer, sender Sender, logger *slog.Logger, options Options) *Queue {
|
||||||
|
if renderer == nil || sender == nil || logger == nil {
|
||||||
|
panic("printqueue.New: renderer, sender and logger must not be nil")
|
||||||
|
}
|
||||||
|
if options.Size <= 0 {
|
||||||
|
panic("printqueue.New: size must be positive")
|
||||||
|
}
|
||||||
|
if options.RetryDelay <= 0 {
|
||||||
|
options.RetryDelay = time.Second
|
||||||
|
}
|
||||||
|
return &Queue{
|
||||||
|
renderer: renderer,
|
||||||
|
sender: sender,
|
||||||
|
logger: logger,
|
||||||
|
options: options,
|
||||||
|
jobs: make(chan queuedJob, options.Size),
|
||||||
|
statuses: make(map[JobID]*Status),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Submit queues job. The job should already be validated so callers can
|
||||||
|
// report problems synchronously; it is validated again when rendered.
|
||||||
|
func (q *Queue) Submit(job receipt.Job) (Status, error) {
|
||||||
|
id, err := typeid.New[JobID]()
|
||||||
|
if err != nil {
|
||||||
|
return Status{}, fmt.Errorf("generating job ID: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
q.mu.Lock()
|
||||||
|
defer q.mu.Unlock()
|
||||||
|
if q.closed {
|
||||||
|
return Status{}, ErrClosed
|
||||||
|
}
|
||||||
|
select {
|
||||||
|
case q.jobs <- queuedJob{id: id, job: job}:
|
||||||
|
default:
|
||||||
|
return Status{}, ErrQueueFull
|
||||||
|
}
|
||||||
|
status := &Status{ID: id, State: StateQueued, CreatedAt: time.Now().UTC()}
|
||||||
|
q.statuses[id] = status
|
||||||
|
return *status, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Status returns the status of job id.
|
||||||
|
func (q *Queue) Status(id JobID) (Status, error) {
|
||||||
|
q.mu.Lock()
|
||||||
|
defer q.mu.Unlock()
|
||||||
|
status, ok := q.statuses[id]
|
||||||
|
if !ok {
|
||||||
|
return Status{}, ErrNotFound
|
||||||
|
}
|
||||||
|
return *status, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pending returns the number of jobs waiting to print.
|
||||||
|
func (q *Queue) Pending() int {
|
||||||
|
return len(q.jobs)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Run prints jobs until ctx is cancelled. A job that is printing when ctx is
|
||||||
|
// cancelled is finished; jobs still waiting are marked failed.
|
||||||
|
func (q *Queue) Run(ctx context.Context) error {
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
q.shutdown()
|
||||||
|
return nil
|
||||||
|
case qj := <-q.jobs:
|
||||||
|
// select picks randomly when both cases are ready, so check
|
||||||
|
// again: no new job may start once shutdown has begun.
|
||||||
|
if ctx.Err() != nil {
|
||||||
|
q.finish(qj.id, 0, errShuttingDown)
|
||||||
|
q.shutdown()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
q.process(ctx, qj)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (q *Queue) process(ctx context.Context, qj queuedJob) {
|
||||||
|
// Detach from shutdown so a receipt that has started is not cut short,
|
||||||
|
// but keep a bound so a stuck printer cannot hold the worker forever.
|
||||||
|
jobCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), jobTimeout)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
q.update(qj.id, func(s *Status) {
|
||||||
|
now := time.Now().UTC()
|
||||||
|
s.State, s.StartedAt = StatePrinting, &now
|
||||||
|
})
|
||||||
|
logger := q.logger.With("job_id", qj.id.String())
|
||||||
|
logger.Info("printing job", "elements", len(qj.job.Elements), "copies", max(qj.job.Copies, 1))
|
||||||
|
|
||||||
|
attempts, err := q.print(ctx, jobCtx, qj.job)
|
||||||
|
q.finish(qj.id, attempts, err)
|
||||||
|
if err != nil {
|
||||||
|
logger.Error("job failed", "attempts", attempts, "err", err)
|
||||||
|
if q.options.OnFailure != nil {
|
||||||
|
q.options.OnFailure(qj.id, err)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
logger.Info("job printed", "attempts", attempts)
|
||||||
|
}
|
||||||
|
|
||||||
|
// print renders job once and sends it, retrying failed sends with backoff.
|
||||||
|
// Retries stop early when runCtx is cancelled.
|
||||||
|
func (q *Queue) print(runCtx, jobCtx context.Context, job receipt.Job) (int, error) {
|
||||||
|
data, err := q.renderer.Render(jobCtx, job)
|
||||||
|
if err != nil {
|
||||||
|
return 0, fmt.Errorf("rendering: %w", err)
|
||||||
|
}
|
||||||
|
delay := q.options.RetryDelay
|
||||||
|
for attempt := 1; ; attempt++ {
|
||||||
|
err := q.sender.Send(jobCtx, data)
|
||||||
|
if err == nil {
|
||||||
|
return attempt, nil
|
||||||
|
}
|
||||||
|
if attempt > q.options.Retries {
|
||||||
|
return attempt, err
|
||||||
|
}
|
||||||
|
q.logger.Warn("send failed, retrying", "attempt", attempt, "retry_in", delay, "err", err)
|
||||||
|
select {
|
||||||
|
case <-time.After(delay):
|
||||||
|
case <-runCtx.Done():
|
||||||
|
return attempt, fmt.Errorf("server shutting down after %d attempts: %w", attempt, err)
|
||||||
|
case <-jobCtx.Done():
|
||||||
|
return attempt, fmt.Errorf("giving up after %d attempts: %w", attempt, err)
|
||||||
|
}
|
||||||
|
delay *= 2
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (q *Queue) finish(id JobID, attempts int, err error) {
|
||||||
|
q.update(id, func(s *Status) {
|
||||||
|
now := time.Now().UTC()
|
||||||
|
s.FinishedAt, s.Attempts = &now, attempts
|
||||||
|
s.State = StateDone
|
||||||
|
if err != nil {
|
||||||
|
s.State, s.Error = StateFailed, err.Error()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
q.mu.Lock()
|
||||||
|
defer q.mu.Unlock()
|
||||||
|
q.finished = append(q.finished, id)
|
||||||
|
for len(q.finished) > q.options.History {
|
||||||
|
delete(q.statuses, q.finished[0])
|
||||||
|
q.finished = q.finished[1:]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (q *Queue) update(id JobID, fn func(*Status)) {
|
||||||
|
q.mu.Lock()
|
||||||
|
defer q.mu.Unlock()
|
||||||
|
if s, ok := q.statuses[id]; ok {
|
||||||
|
fn(s)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// shutdown stops accepting jobs and fails those still waiting.
|
||||||
|
func (q *Queue) shutdown() {
|
||||||
|
q.mu.Lock()
|
||||||
|
q.closed = true
|
||||||
|
q.mu.Unlock()
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case qj := <-q.jobs:
|
||||||
|
q.finish(qj.id, 0, errShuttingDown)
|
||||||
|
default:
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,255 @@
|
|||||||
|
package printqueue_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"log/slog"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/printqueue"
|
||||||
|
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/receipt"
|
||||||
|
)
|
||||||
|
|
||||||
|
type fakeRenderer struct{ err error }
|
||||||
|
|
||||||
|
func (f fakeRenderer) Render(_ context.Context, job receipt.Job) ([]byte, error) {
|
||||||
|
if f.err != nil {
|
||||||
|
return nil, f.err
|
||||||
|
}
|
||||||
|
return []byte(job.Elements[0].Text), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// fakeSender fails the first failures sends, then records data.
|
||||||
|
type fakeSender struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
failures int
|
||||||
|
sent []string
|
||||||
|
block chan struct{} // if set, Send waits for it to close
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fakeSender) Send(_ context.Context, data []byte) error {
|
||||||
|
if f.block != nil {
|
||||||
|
<-f.block
|
||||||
|
}
|
||||||
|
f.mu.Lock()
|
||||||
|
defer f.mu.Unlock()
|
||||||
|
if f.failures > 0 {
|
||||||
|
f.failures--
|
||||||
|
return errors.New("printer offline")
|
||||||
|
}
|
||||||
|
f.sent = append(f.sent, string(data))
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fakeSender) Sent() []string {
|
||||||
|
f.mu.Lock()
|
||||||
|
defer f.mu.Unlock()
|
||||||
|
return append([]string(nil), f.sent...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func job(text string) receipt.Job {
|
||||||
|
return receipt.Job{Elements: []receipt.Element{{Type: "text", Text: text}}}
|
||||||
|
}
|
||||||
|
|
||||||
|
func discardLogger() *slog.Logger {
|
||||||
|
return slog.New(slog.NewTextHandler(io.Discard, nil))
|
||||||
|
}
|
||||||
|
|
||||||
|
func newQueue(r printqueue.Renderer, s printqueue.Sender, opts printqueue.Options) *printqueue.Queue {
|
||||||
|
if opts.Size == 0 {
|
||||||
|
opts.Size = 10
|
||||||
|
}
|
||||||
|
if opts.History == 0 {
|
||||||
|
opts.History = 100
|
||||||
|
}
|
||||||
|
if opts.RetryDelay == 0 {
|
||||||
|
opts.RetryDelay = time.Millisecond
|
||||||
|
}
|
||||||
|
return printqueue.New(r, s, discardLogger(), opts)
|
||||||
|
}
|
||||||
|
|
||||||
|
// startQueue runs q until the test ends and returns a func that stops it and
|
||||||
|
// waits for Run to return.
|
||||||
|
func startQueue(t *testing.T, q *printqueue.Queue) (stop func()) {
|
||||||
|
t.Helper()
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
done := make(chan struct{})
|
||||||
|
go func() {
|
||||||
|
defer close(done)
|
||||||
|
if err := q.Run(ctx); err != nil {
|
||||||
|
t.Error(err)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
var once sync.Once
|
||||||
|
stop = func() { once.Do(func() { cancel(); <-done }) }
|
||||||
|
t.Cleanup(stop)
|
||||||
|
return stop
|
||||||
|
}
|
||||||
|
|
||||||
|
func waitForState(t *testing.T, q *printqueue.Queue, id printqueue.JobID, want printqueue.State) printqueue.Status {
|
||||||
|
t.Helper()
|
||||||
|
deadline := time.Now().Add(5 * time.Second)
|
||||||
|
for time.Now().Before(deadline) {
|
||||||
|
st, err := q.Status(id)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if st.State == want {
|
||||||
|
return st
|
||||||
|
}
|
||||||
|
time.Sleep(5 * time.Millisecond)
|
||||||
|
}
|
||||||
|
st, _ := q.Status(id)
|
||||||
|
t.Fatalf("job %s state = %s, want %s", id, st.State, want)
|
||||||
|
return st
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSubmitAndPrintInOrder(t *testing.T) {
|
||||||
|
sender := &fakeSender{}
|
||||||
|
q := newQueue(fakeRenderer{}, sender, printqueue.Options{})
|
||||||
|
startQueue(t, q)
|
||||||
|
|
||||||
|
var last printqueue.Status
|
||||||
|
for _, text := range []string{"one", "two", "three"} {
|
||||||
|
st, err := q.Submit(job(text))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if st.State != printqueue.StateQueued || !strings.HasPrefix(st.ID.String(), "job_") {
|
||||||
|
t.Errorf("submit status = %+v", st)
|
||||||
|
}
|
||||||
|
last = st
|
||||||
|
}
|
||||||
|
done := waitForState(t, q, last.ID, printqueue.StateDone)
|
||||||
|
if done.StartedAt == nil || done.FinishedAt == nil || done.Attempts != 1 {
|
||||||
|
t.Errorf("done status = %+v", done)
|
||||||
|
}
|
||||||
|
if got := sender.Sent(); strings.Join(got, ",") != "one,two,three" {
|
||||||
|
t.Errorf("sent %v, want one,two,three", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRetriesThenSucceeds(t *testing.T) {
|
||||||
|
sender := &fakeSender{failures: 2}
|
||||||
|
q := newQueue(fakeRenderer{}, sender, printqueue.Options{Retries: 3})
|
||||||
|
startQueue(t, q)
|
||||||
|
st, _ := q.Submit(job("x"))
|
||||||
|
done := waitForState(t, q, st.ID, printqueue.StateDone)
|
||||||
|
if done.Attempts != 3 {
|
||||||
|
t.Errorf("attempts = %d, want 3", done.Attempts)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFailsAfterRetries(t *testing.T) {
|
||||||
|
var reported []printqueue.JobID
|
||||||
|
var mu sync.Mutex
|
||||||
|
sender := &fakeSender{failures: 10}
|
||||||
|
q := newQueue(fakeRenderer{}, sender, printqueue.Options{
|
||||||
|
Retries: 2,
|
||||||
|
OnFailure: func(id printqueue.JobID, _ error) {
|
||||||
|
mu.Lock()
|
||||||
|
defer mu.Unlock()
|
||||||
|
reported = append(reported, id)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
startQueue(t, q)
|
||||||
|
st, _ := q.Submit(job("x"))
|
||||||
|
failed := waitForState(t, q, st.ID, printqueue.StateFailed)
|
||||||
|
if failed.Attempts != 3 || !strings.Contains(failed.Error, "printer offline") {
|
||||||
|
t.Errorf("failed status = %+v", failed)
|
||||||
|
}
|
||||||
|
mu.Lock()
|
||||||
|
defer mu.Unlock()
|
||||||
|
if len(reported) != 1 || reported[0] != st.ID {
|
||||||
|
t.Errorf("OnFailure got %v", reported)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRenderFailureIsNotRetried(t *testing.T) {
|
||||||
|
sender := &fakeSender{}
|
||||||
|
q := newQueue(fakeRenderer{err: errors.New("image blocked")}, sender, printqueue.Options{Retries: 3})
|
||||||
|
startQueue(t, q)
|
||||||
|
st, _ := q.Submit(job("x"))
|
||||||
|
failed := waitForState(t, q, st.ID, printqueue.StateFailed)
|
||||||
|
if !strings.Contains(failed.Error, "image blocked") || len(sender.Sent()) != 0 {
|
||||||
|
t.Errorf("failed status = %+v, sent %v", failed, sender.Sent())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestQueueFull(t *testing.T) {
|
||||||
|
q := newQueue(fakeRenderer{}, &fakeSender{}, printqueue.Options{Size: 2})
|
||||||
|
// Not running, so nothing drains the queue.
|
||||||
|
for range 2 {
|
||||||
|
if _, err := q.Submit(job("x")); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, err := q.Submit(job("x")); !errors.Is(err, printqueue.ErrQueueFull) {
|
||||||
|
t.Errorf("err = %v, want ErrQueueFull", err)
|
||||||
|
}
|
||||||
|
if q.Pending() != 2 {
|
||||||
|
t.Errorf("Pending = %d, want 2", q.Pending())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestShutdownFinishesCurrentJobAndFailsWaiting(t *testing.T) {
|
||||||
|
sender := &fakeSender{block: make(chan struct{})}
|
||||||
|
q := newQueue(fakeRenderer{}, sender, printqueue.Options{})
|
||||||
|
stop := startQueue(t, q)
|
||||||
|
|
||||||
|
first, _ := q.Submit(job("first"))
|
||||||
|
waitForState(t, q, first.ID, printqueue.StatePrinting)
|
||||||
|
second, _ := q.Submit(job("second"))
|
||||||
|
|
||||||
|
stopped := make(chan struct{})
|
||||||
|
go func() { stop(); close(stopped) }()
|
||||||
|
time.Sleep(20 * time.Millisecond) // let Run observe the cancellation
|
||||||
|
close(sender.block) // the in-flight send completes
|
||||||
|
<-stopped
|
||||||
|
|
||||||
|
if st, _ := q.Status(first.ID); st.State != printqueue.StateDone {
|
||||||
|
t.Errorf("in-flight job state = %s, want done", st.State)
|
||||||
|
}
|
||||||
|
if st, _ := q.Status(second.ID); st.State != printqueue.StateFailed || !strings.Contains(st.Error, "shutting down") {
|
||||||
|
t.Errorf("waiting job = %+v, want failed with shutting down", st)
|
||||||
|
}
|
||||||
|
if _, err := q.Submit(job("late")); !errors.Is(err, printqueue.ErrClosed) {
|
||||||
|
t.Errorf("submit after shutdown err = %v, want ErrClosed", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHistoryEviction(t *testing.T) {
|
||||||
|
sender := &fakeSender{}
|
||||||
|
q := newQueue(fakeRenderer{}, sender, printqueue.Options{History: 2})
|
||||||
|
startQueue(t, q)
|
||||||
|
var ids []printqueue.JobID
|
||||||
|
for range 3 {
|
||||||
|
st, _ := q.Submit(job("x"))
|
||||||
|
ids = append(ids, st.ID)
|
||||||
|
waitForState(t, q, st.ID, printqueue.StateDone)
|
||||||
|
}
|
||||||
|
if _, err := q.Status(ids[0]); !errors.Is(err, printqueue.ErrNotFound) {
|
||||||
|
t.Errorf("oldest job err = %v, want ErrNotFound", err)
|
||||||
|
}
|
||||||
|
if _, err := q.Status(ids[2]); err != nil {
|
||||||
|
t.Errorf("newest job err = %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestParseJobID(t *testing.T) {
|
||||||
|
q := newQueue(fakeRenderer{}, &fakeSender{}, printqueue.Options{})
|
||||||
|
st, _ := q.Submit(job("x"))
|
||||||
|
parsed, err := printqueue.ParseJobID(st.ID.String())
|
||||||
|
if err != nil || parsed != st.ID {
|
||||||
|
t.Errorf("ParseJobID(%s) = %v, %v", st.ID, parsed, err)
|
||||||
|
}
|
||||||
|
for _, bad := range []string{"", "nope", "req_01h455vb4pex5vsknk084sn02q", "job_zzz"} {
|
||||||
|
if _, err := printqueue.ParseJobID(bad); err == nil {
|
||||||
|
t.Errorf("ParseJobID(%q) succeeded", bad)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
// Package raster prepares images for thermal printing: it decodes them within
|
||||||
|
// a pixel budget, scales them to the print head width, and dithers them to
|
||||||
|
// pure black and white.
|
||||||
|
package raster
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"image"
|
||||||
|
"image/color"
|
||||||
|
"image/draw"
|
||||||
|
|
||||||
|
// Register the formats Decode accepts.
|
||||||
|
_ "image/gif" // registers GIF decoding
|
||||||
|
_ "image/jpeg" // registers JPEG decoding
|
||||||
|
_ "image/png" // registers PNG decoding
|
||||||
|
|
||||||
|
xdraw "golang.org/x/image/draw"
|
||||||
|
_ "golang.org/x/image/webp" // registers WebP decoding
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
// ErrTooLarge is returned when an image exceeds the pixel budget.
|
||||||
|
ErrTooLarge = errors.New("raster: image exceeds pixel limit")
|
||||||
|
|
||||||
|
// ErrInvalidSize is returned for zero or negative target sizes.
|
||||||
|
ErrInvalidSize = errors.New("raster: invalid size")
|
||||||
|
)
|
||||||
|
|
||||||
|
// Decode decodes PNG, JPEG, GIF or WebP data. The header is checked first,
|
||||||
|
// so an image whose declared size exceeds maxPixels is rejected before any
|
||||||
|
// pixel memory is allocated.
|
||||||
|
func Decode(data []byte, maxPixels int) (image.Image, error) {
|
||||||
|
cfg, format, err := image.DecodeConfig(bytes.NewReader(data))
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("reading image header: %w", err)
|
||||||
|
}
|
||||||
|
if cfg.Width <= 0 || cfg.Height <= 0 {
|
||||||
|
return nil, fmt.Errorf("%w: %dx%d", ErrInvalidSize, cfg.Width, cfg.Height)
|
||||||
|
}
|
||||||
|
if int64(cfg.Width)*int64(cfg.Height) > int64(maxPixels) {
|
||||||
|
return nil, fmt.Errorf("%w: %dx%d is more than %d pixels", ErrTooLarge, cfg.Width, cfg.Height, maxPixels)
|
||||||
|
}
|
||||||
|
img, _, err := image.Decode(bytes.NewReader(data))
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("decoding %s image: %w", format, err)
|
||||||
|
}
|
||||||
|
return img, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// palette is the two-colour palette thermal printers can reproduce.
|
||||||
|
// Index 0 is white so a freshly allocated image is blank paper.
|
||||||
|
func palette() color.Palette {
|
||||||
|
return color.Palette{color.White, color.Black}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Monochrome scales img to width dots, keeping its aspect ratio, composites it
|
||||||
|
// onto white paper, and Floyd–Steinberg dithers it to black and white.
|
||||||
|
func Monochrome(img image.Image, width int) (*image.Paletted, error) {
|
||||||
|
src := img.Bounds()
|
||||||
|
if width <= 0 || src.Dx() <= 0 || src.Dy() <= 0 {
|
||||||
|
return nil, fmt.Errorf("%w: cannot scale %dx%d to width %d", ErrInvalidSize, src.Dx(), src.Dy(), width)
|
||||||
|
}
|
||||||
|
height := max(1, int(int64(src.Dy())*int64(width)/int64(src.Dx())))
|
||||||
|
|
||||||
|
// Scale onto white grayscale so transparency becomes paper and the
|
||||||
|
// dither works on luminance rather than RGB distance.
|
||||||
|
gray := image.NewGray(image.Rect(0, 0, width, height))
|
||||||
|
draw.Draw(gray, gray.Bounds(), image.White, image.Point{}, draw.Src)
|
||||||
|
xdraw.CatmullRom.Scale(gray, gray.Bounds(), img, src, draw.Over, nil)
|
||||||
|
|
||||||
|
out := image.NewPaletted(gray.Bounds(), palette())
|
||||||
|
draw.FloydSteinberg.Draw(out, out.Bounds(), gray, image.Point{})
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Place returns a width-dot-wide white canvas with img drawn at x. It is used
|
||||||
|
// to align images, because printers do not apply justification to raster
|
||||||
|
// images consistently.
|
||||||
|
func Place(img *image.Paletted, width, x int) (*image.Paletted, error) {
|
||||||
|
b := img.Bounds()
|
||||||
|
if width < b.Dx() || x < 0 || x+b.Dx() > width {
|
||||||
|
return nil, fmt.Errorf("%w: cannot place %d-dot image at %d on %d dots", ErrInvalidSize, b.Dx(), x, width)
|
||||||
|
}
|
||||||
|
if x == 0 && width == b.Dx() {
|
||||||
|
return img, nil
|
||||||
|
}
|
||||||
|
out := image.NewPaletted(image.Rect(0, 0, width, b.Dy()), palette())
|
||||||
|
draw.Draw(out, image.Rect(x, 0, x+b.Dx(), b.Dy()), img, b.Min, draw.Src)
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,133 @@
|
|||||||
|
package raster_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"errors"
|
||||||
|
"image"
|
||||||
|
"image/color"
|
||||||
|
"image/png"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/raster"
|
||||||
|
)
|
||||||
|
|
||||||
|
func encodePNG(t *testing.T, img image.Image) []byte {
|
||||||
|
t.Helper()
|
||||||
|
var buf bytes.Buffer
|
||||||
|
if err := png.Encode(&buf, img); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return buf.Bytes()
|
||||||
|
}
|
||||||
|
|
||||||
|
func gradient(w, h int) *image.Gray {
|
||||||
|
img := image.NewGray(image.Rect(0, 0, w, h))
|
||||||
|
for y := range h {
|
||||||
|
for x := range w {
|
||||||
|
img.SetGray(x, y, color.Gray{Y: uint8(x * 255 / max(1, w-1))})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return img
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDecode(t *testing.T) {
|
||||||
|
data := encodePNG(t, gradient(40, 20))
|
||||||
|
img, err := raster.Decode(data, 1000)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if img.Bounds().Dx() != 40 || img.Bounds().Dy() != 20 {
|
||||||
|
t.Errorf("bounds = %v", img.Bounds())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDecodeRejectsOversizedBeforeDecoding(t *testing.T) {
|
||||||
|
data := encodePNG(t, gradient(40, 20))
|
||||||
|
if _, err := raster.Decode(data, 799); !errors.Is(err, raster.ErrTooLarge) {
|
||||||
|
t.Errorf("err = %v, want ErrTooLarge", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDecodeRejectsGarbage(t *testing.T) {
|
||||||
|
if _, err := raster.Decode([]byte("not an image"), 1000); err == nil {
|
||||||
|
t.Error("expected an error")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMonochromeScalesAndKeepsAspect(t *testing.T) {
|
||||||
|
out, err := raster.Monochrome(gradient(1152, 400), 576)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if got := out.Bounds(); got.Dx() != 576 || got.Dy() != 200 {
|
||||||
|
t.Errorf("bounds = %v, want 576x200", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMonochromeIsBlackAndWhiteAndDithers(t *testing.T) {
|
||||||
|
out, err := raster.Monochrome(gradient(200, 50), 200)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(out.Palette) != 2 {
|
||||||
|
t.Fatalf("palette has %d colours, want 2", len(out.Palette))
|
||||||
|
}
|
||||||
|
// A dither of a left-to-right gradient has mixed pixels in the middle,
|
||||||
|
// unlike a hard threshold which would split it into two solid halves.
|
||||||
|
black := 0
|
||||||
|
for y := range 50 {
|
||||||
|
for x := 90; x < 110; x++ {
|
||||||
|
if out.ColorIndexAt(x, y) == 1 {
|
||||||
|
black++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if total := 50 * 20; black == 0 || black == total {
|
||||||
|
t.Errorf("mid-gradient has %d/%d black pixels, want a mix", black, total)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMonochromeTransparentBecomesWhite(t *testing.T) {
|
||||||
|
src := image.NewNRGBA(image.Rect(0, 0, 16, 16)) // fully transparent
|
||||||
|
out, err := raster.Monochrome(src, 16)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for i, idx := range out.Pix {
|
||||||
|
if idx != 0 {
|
||||||
|
t.Fatalf("pixel %d is black, want white paper", i)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMonochromeInvalidWidth(t *testing.T) {
|
||||||
|
if _, err := raster.Monochrome(gradient(10, 10), 0); !errors.Is(err, raster.ErrInvalidSize) {
|
||||||
|
t.Errorf("err = %v, want ErrInvalidSize", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPlace(t *testing.T) {
|
||||||
|
img, err := raster.Monochrome(image.NewGray(image.Rect(0, 0, 8, 2)), 8) // all black
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
out, err := raster.Place(img, 24, 8)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if out.Bounds().Dx() != 24 {
|
||||||
|
t.Fatalf("width = %d", out.Bounds().Dx())
|
||||||
|
}
|
||||||
|
for x := range 24 {
|
||||||
|
want := uint8(0)
|
||||||
|
if x >= 8 && x < 16 {
|
||||||
|
want = 1
|
||||||
|
}
|
||||||
|
if got := out.ColorIndexAt(x, 0); got != want {
|
||||||
|
t.Errorf("x=%d index=%d, want %d", x, got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, err := raster.Place(img, 12, 8); !errors.Is(err, raster.ErrInvalidSize) {
|
||||||
|
t.Errorf("overflowing place err = %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,389 @@
|
|||||||
|
// Package receipt defines print jobs, validates them, and lays them out as
|
||||||
|
// ESC/POS command streams with code page transcoding and word wrapping.
|
||||||
|
package receipt
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/hex"
|
||||||
|
"fmt"
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/escpos"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Element types.
|
||||||
|
const (
|
||||||
|
TypeText = "text"
|
||||||
|
TypeFeed = "feed"
|
||||||
|
TypeQR = "qr"
|
||||||
|
TypeBarcode = "barcode"
|
||||||
|
TypeImage = "image"
|
||||||
|
TypeRaw = "raw"
|
||||||
|
TypeCut = "cut"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Job limits.
|
||||||
|
const (
|
||||||
|
MaxElements = 500
|
||||||
|
MaxCopies = 5
|
||||||
|
)
|
||||||
|
|
||||||
|
// Element defaults.
|
||||||
|
const (
|
||||||
|
defaultQRSize = 6
|
||||||
|
defaultBarcodeHeight = 80
|
||||||
|
defaultBarcodeWidth = 3
|
||||||
|
)
|
||||||
|
|
||||||
|
// Job is a receipt to print.
|
||||||
|
type Job struct {
|
||||||
|
Elements []Element `json:"elements"`
|
||||||
|
|
||||||
|
// Copies is how many times the receipt is printed, each with its own
|
||||||
|
// cut. Zero means one.
|
||||||
|
Copies int `json:"copies,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Element is one item on a receipt. Type selects which fields apply; fields
|
||||||
|
// that do not apply to the type are ignored. Width and Height mean character
|
||||||
|
// multipliers for text, module width and bar height for barcodes, and target
|
||||||
|
// width in dots for images.
|
||||||
|
type Element struct {
|
||||||
|
Type string `json:"type"`
|
||||||
|
|
||||||
|
// Text.
|
||||||
|
Text string `json:"text,omitempty"`
|
||||||
|
Bold bool `json:"bold,omitempty"`
|
||||||
|
Size int `json:"size,omitempty"`
|
||||||
|
Width int `json:"width,omitempty"`
|
||||||
|
Height int `json:"height,omitempty"`
|
||||||
|
Font string `json:"font,omitempty"`
|
||||||
|
Align string `json:"align,omitempty"`
|
||||||
|
Underline int `json:"underline,omitempty"`
|
||||||
|
Invert bool `json:"invert,omitempty"`
|
||||||
|
Newline *bool `json:"newline,omitempty"`
|
||||||
|
Wrap *bool `json:"wrap,omitempty"`
|
||||||
|
|
||||||
|
// Feed.
|
||||||
|
Lines int `json:"lines,omitempty"`
|
||||||
|
|
||||||
|
// QR code and barcode.
|
||||||
|
Data string `json:"data,omitempty"`
|
||||||
|
Correction string `json:"correction,omitempty"`
|
||||||
|
Symbology string `json:"symbology,omitempty"`
|
||||||
|
HRI string `json:"hri,omitempty"`
|
||||||
|
|
||||||
|
// Image.
|
||||||
|
URL string `json:"url,omitempty"`
|
||||||
|
Base64 string `json:"base64,omitempty"`
|
||||||
|
|
||||||
|
// Raw.
|
||||||
|
Hex string `json:"hex,omitempty"`
|
||||||
|
|
||||||
|
// Cut.
|
||||||
|
Mode string `json:"mode,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ValidationError lists every problem found in a job.
|
||||||
|
type ValidationError struct {
|
||||||
|
Problems []string
|
||||||
|
}
|
||||||
|
|
||||||
|
// Error implements error.
|
||||||
|
func (e *ValidationError) Error() string {
|
||||||
|
return "invalid job: " + strings.Join(e.Problems, "; ")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate checks the whole job and reports every problem, so nothing is sent
|
||||||
|
// to the printer unless the entire receipt can be printed.
|
||||||
|
func (j Job) Validate() error {
|
||||||
|
var problems []string
|
||||||
|
switch {
|
||||||
|
case len(j.Elements) == 0:
|
||||||
|
problems = append(problems, "elements: at least one element is required")
|
||||||
|
case len(j.Elements) > MaxElements:
|
||||||
|
problems = append(problems, fmt.Sprintf("elements: %d elements, limit is %d", len(j.Elements), MaxElements))
|
||||||
|
}
|
||||||
|
if j.Copies < 0 || j.Copies > MaxCopies {
|
||||||
|
problems = append(problems, fmt.Sprintf("copies must be 1-%d", MaxCopies))
|
||||||
|
}
|
||||||
|
for i, el := range j.Elements {
|
||||||
|
if err := el.validate(); err != nil {
|
||||||
|
problems = append(problems, fmt.Sprintf("elements[%d] (%s): %v", i, el.Type, err))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(problems) > 0 {
|
||||||
|
return &ValidationError{Problems: problems}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (j Job) copies() int {
|
||||||
|
return max(j.Copies, 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (el Element) validate() error {
|
||||||
|
var err error
|
||||||
|
switch el.Type {
|
||||||
|
case TypeText:
|
||||||
|
_, err = el.textSpec()
|
||||||
|
case TypeFeed:
|
||||||
|
_, err = el.feedLines()
|
||||||
|
case TypeQR:
|
||||||
|
_, err = el.qrSpec()
|
||||||
|
case TypeBarcode:
|
||||||
|
_, err = el.barcodeSpec()
|
||||||
|
case TypeImage:
|
||||||
|
_, err = el.imageSpec()
|
||||||
|
case TypeRaw:
|
||||||
|
_, err = el.rawBytes()
|
||||||
|
case TypeCut:
|
||||||
|
_, err = el.cutMode()
|
||||||
|
case "":
|
||||||
|
err = fmt.Errorf("type is required")
|
||||||
|
default:
|
||||||
|
err = fmt.Errorf("unknown type %q (want text, feed, qr, barcode, image, raw or cut)", el.Type)
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
type textSpec struct {
|
||||||
|
width, height int
|
||||||
|
bold bool
|
||||||
|
font escpos.Font
|
||||||
|
align escpos.Justification
|
||||||
|
underline escpos.Underline
|
||||||
|
invert bool
|
||||||
|
newline bool
|
||||||
|
wrap bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func (el Element) textSpec() (textSpec, error) {
|
||||||
|
s := textSpec{
|
||||||
|
width: 1,
|
||||||
|
height: 1,
|
||||||
|
bold: el.Bold,
|
||||||
|
invert: el.Invert,
|
||||||
|
newline: el.Newline == nil || *el.Newline,
|
||||||
|
wrap: el.Wrap == nil || *el.Wrap,
|
||||||
|
}
|
||||||
|
if el.Size != 0 {
|
||||||
|
s.width, s.height = el.Size, el.Size
|
||||||
|
}
|
||||||
|
if el.Width != 0 {
|
||||||
|
s.width = el.Width
|
||||||
|
}
|
||||||
|
if el.Height != 0 {
|
||||||
|
s.height = el.Height
|
||||||
|
}
|
||||||
|
if s.width < 1 || s.width > escpos.MaxCharacterScale || s.height < 1 || s.height > escpos.MaxCharacterScale {
|
||||||
|
return s, fmt.Errorf("size, width and height must be 1-%d", escpos.MaxCharacterScale)
|
||||||
|
}
|
||||||
|
var err error
|
||||||
|
if s.font, err = parseFont(el.Font); err != nil {
|
||||||
|
return s, err
|
||||||
|
}
|
||||||
|
if s.align, err = parseAlign(el.Align); err != nil {
|
||||||
|
return s, err
|
||||||
|
}
|
||||||
|
switch el.Underline {
|
||||||
|
case 0, 1, 2:
|
||||||
|
s.underline = escpos.Underline(el.Underline)
|
||||||
|
default:
|
||||||
|
return s, fmt.Errorf("underline must be 0, 1 or 2")
|
||||||
|
}
|
||||||
|
return s, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (el Element) feedLines() (uint8, error) {
|
||||||
|
switch {
|
||||||
|
case el.Lines == 0:
|
||||||
|
return 1, nil
|
||||||
|
case el.Lines < 1 || el.Lines > 255:
|
||||||
|
return 0, fmt.Errorf("lines must be 1-255")
|
||||||
|
}
|
||||||
|
return uint8(el.Lines), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type qrSpec struct {
|
||||||
|
size int
|
||||||
|
correction escpos.QRCorrection
|
||||||
|
align escpos.Justification
|
||||||
|
}
|
||||||
|
|
||||||
|
func (el Element) qrSpec() (qrSpec, error) {
|
||||||
|
s := qrSpec{size: defaultQRSize, correction: escpos.QRCorrectionM}
|
||||||
|
if el.Size != 0 {
|
||||||
|
s.size = el.Size
|
||||||
|
}
|
||||||
|
switch {
|
||||||
|
case el.Data == "":
|
||||||
|
return s, fmt.Errorf("data is required")
|
||||||
|
case len(el.Data) > escpos.MaxQRData:
|
||||||
|
return s, fmt.Errorf("data is %d bytes, limit is %d", len(el.Data), escpos.MaxQRData)
|
||||||
|
case s.size < escpos.MinQRModuleSize || s.size > escpos.MaxQRModuleSize:
|
||||||
|
return s, fmt.Errorf("size must be %d-%d", escpos.MinQRModuleSize, escpos.MaxQRModuleSize)
|
||||||
|
}
|
||||||
|
var err error
|
||||||
|
if el.Correction != "" {
|
||||||
|
if s.correction, err = escpos.ParseQRCorrection(el.Correction); err != nil {
|
||||||
|
return s, fmt.Errorf("correction must be L, M, Q or H")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if s.align, err = parseAlign(el.Align); err != nil {
|
||||||
|
return s, err
|
||||||
|
}
|
||||||
|
return s, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type barcodeSpec struct {
|
||||||
|
symbology escpos.Symbology
|
||||||
|
height int
|
||||||
|
width int
|
||||||
|
hri escpos.HRIPosition
|
||||||
|
align escpos.Justification
|
||||||
|
}
|
||||||
|
|
||||||
|
func (el Element) barcodeSpec() (barcodeSpec, error) {
|
||||||
|
s := barcodeSpec{height: defaultBarcodeHeight, width: defaultBarcodeWidth, hri: escpos.HRIBelow}
|
||||||
|
if el.Symbology == "" {
|
||||||
|
return s, fmt.Errorf("symbology is required (ean13, ean8, upca, upce, code39 or code128)")
|
||||||
|
}
|
||||||
|
var err error
|
||||||
|
if s.symbology, err = escpos.ParseSymbology(el.Symbology); err != nil {
|
||||||
|
return s, fmt.Errorf("unknown symbology %q (want ean13, ean8, upca, upce, code39 or code128)", el.Symbology)
|
||||||
|
}
|
||||||
|
if err := escpos.ValidateBarcode(s.symbology, el.Data); err != nil {
|
||||||
|
return s, fmt.Errorf("data: %w", err)
|
||||||
|
}
|
||||||
|
if el.Height != 0 {
|
||||||
|
s.height = el.Height
|
||||||
|
}
|
||||||
|
if el.Width != 0 {
|
||||||
|
s.width = el.Width
|
||||||
|
}
|
||||||
|
if s.height < 1 || s.height > 255 {
|
||||||
|
return s, fmt.Errorf("height must be 1-255 dots")
|
||||||
|
}
|
||||||
|
if s.width < escpos.MinBarcodeWidth || s.width > escpos.MaxBarcodeWidth {
|
||||||
|
return s, fmt.Errorf("width must be %d-%d", escpos.MinBarcodeWidth, escpos.MaxBarcodeWidth)
|
||||||
|
}
|
||||||
|
switch strings.ToLower(el.HRI) {
|
||||||
|
case "", "below":
|
||||||
|
s.hri = escpos.HRIBelow
|
||||||
|
case "none":
|
||||||
|
s.hri = escpos.HRINone
|
||||||
|
case "above":
|
||||||
|
s.hri = escpos.HRIAbove
|
||||||
|
case "both":
|
||||||
|
s.hri = escpos.HRIBoth
|
||||||
|
default:
|
||||||
|
return s, fmt.Errorf("hri must be none, above, below or both")
|
||||||
|
}
|
||||||
|
if s.align, err = parseAlign(el.Align); err != nil {
|
||||||
|
return s, err
|
||||||
|
}
|
||||||
|
return s, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type imageSpec struct {
|
||||||
|
url string
|
||||||
|
data []byte
|
||||||
|
width int
|
||||||
|
align escpos.Justification
|
||||||
|
}
|
||||||
|
|
||||||
|
func (el Element) imageSpec() (imageSpec, error) {
|
||||||
|
s := imageSpec{width: el.Width}
|
||||||
|
switch {
|
||||||
|
case el.URL != "" && el.Base64 != "":
|
||||||
|
return s, fmt.Errorf("set url or base64, not both")
|
||||||
|
case el.URL != "":
|
||||||
|
u, err := url.Parse(el.URL)
|
||||||
|
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
|
||||||
|
return s, fmt.Errorf("url must be an absolute http or https URL")
|
||||||
|
}
|
||||||
|
s.url = el.URL
|
||||||
|
case el.Base64 != "":
|
||||||
|
data, err := decodeBase64Image(el.Base64)
|
||||||
|
if err != nil {
|
||||||
|
return s, fmt.Errorf("base64: %w", err)
|
||||||
|
}
|
||||||
|
s.data = data
|
||||||
|
default:
|
||||||
|
return s, fmt.Errorf("url or base64 is required")
|
||||||
|
}
|
||||||
|
if s.width < 0 {
|
||||||
|
return s, fmt.Errorf("width must be positive")
|
||||||
|
}
|
||||||
|
var err error
|
||||||
|
if s.align, err = parseAlign(el.Align); err != nil {
|
||||||
|
return s, err
|
||||||
|
}
|
||||||
|
return s, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// decodeBase64Image accepts standard base64, with or without padding, and
|
||||||
|
// data URIs such as "data:image/png;base64,....".
|
||||||
|
func decodeBase64Image(s string) ([]byte, error) {
|
||||||
|
if rest, ok := strings.CutPrefix(s, "data:"); ok {
|
||||||
|
_, payload, found := strings.Cut(rest, ",")
|
||||||
|
if !found {
|
||||||
|
return nil, fmt.Errorf("malformed data URI")
|
||||||
|
}
|
||||||
|
s = payload
|
||||||
|
}
|
||||||
|
s = strings.TrimSpace(s)
|
||||||
|
if data, err := base64.StdEncoding.DecodeString(s); err == nil {
|
||||||
|
return data, nil
|
||||||
|
}
|
||||||
|
data, err := base64.RawStdEncoding.DecodeString(strings.TrimRight(s, "="))
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("not valid base64")
|
||||||
|
}
|
||||||
|
return data, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (el Element) rawBytes() ([]byte, error) {
|
||||||
|
if el.Hex == "" {
|
||||||
|
return nil, fmt.Errorf("hex is required")
|
||||||
|
}
|
||||||
|
data, err := hex.DecodeString(strings.ReplaceAll(el.Hex, " ", ""))
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("hex: %v", err)
|
||||||
|
}
|
||||||
|
return data, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (el Element) cutMode() (escpos.CutMode, error) {
|
||||||
|
switch strings.ToLower(el.Mode) {
|
||||||
|
case "", "partial":
|
||||||
|
return escpos.CutPartial, nil
|
||||||
|
case "full":
|
||||||
|
return escpos.CutFull, nil
|
||||||
|
}
|
||||||
|
return 0, fmt.Errorf("mode must be partial or full")
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseAlign(s string) (escpos.Justification, error) {
|
||||||
|
switch strings.ToLower(s) {
|
||||||
|
case "", "left":
|
||||||
|
return escpos.JustifyLeft, nil
|
||||||
|
case "center", "centre":
|
||||||
|
return escpos.JustifyCenter, nil
|
||||||
|
case "right":
|
||||||
|
return escpos.JustifyRight, nil
|
||||||
|
}
|
||||||
|
return 0, fmt.Errorf("align must be left, center or right")
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseFont(s string) (escpos.Font, error) {
|
||||||
|
switch strings.ToLower(s) {
|
||||||
|
case "", "a":
|
||||||
|
return escpos.FontA, nil
|
||||||
|
case "b":
|
||||||
|
return escpos.FontB, nil
|
||||||
|
}
|
||||||
|
return 0, fmt.Errorf("font must be a or b")
|
||||||
|
}
|
||||||
@@ -0,0 +1,136 @@
|
|||||||
|
package receipt
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/escpos"
|
||||||
|
)
|
||||||
|
|
||||||
|
// tabWidth matches the printer's default horizontal tab stops.
|
||||||
|
const tabWidth = 8
|
||||||
|
|
||||||
|
// sanitize removes control characters that would be read as printer
|
||||||
|
// commands, keeping newlines and tabs, and normalises CRLF to LF.
|
||||||
|
func sanitize(s string) string {
|
||||||
|
return strings.Map(func(r rune) rune {
|
||||||
|
if escpos.IsControl(r) {
|
||||||
|
return -1
|
||||||
|
}
|
||||||
|
return r
|
||||||
|
}, s)
|
||||||
|
}
|
||||||
|
|
||||||
|
// expandTabs replaces tabs with spaces up to the next tab stop. startCol is
|
||||||
|
// the column the text starts at; columns restart at zero after a newline.
|
||||||
|
func expandTabs(s string, startCol int) string {
|
||||||
|
if !strings.ContainsRune(s, '\t') {
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
var b strings.Builder
|
||||||
|
col := startCol
|
||||||
|
for _, r := range s {
|
||||||
|
switch r {
|
||||||
|
case '\t':
|
||||||
|
n := tabWidth - col%tabWidth
|
||||||
|
b.WriteString(strings.Repeat(" ", n))
|
||||||
|
col += n
|
||||||
|
case '\n':
|
||||||
|
b.WriteRune(r)
|
||||||
|
col = 0
|
||||||
|
default:
|
||||||
|
b.WriteRune(r)
|
||||||
|
col++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return b.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
// wrap breaks text into lines of at most width runes, so that no word is
|
||||||
|
// split across lines. The first line has only first runes available, because
|
||||||
|
// it continues whatever is already on the current printer line. A first line
|
||||||
|
// of "" means the text must start on a fresh line.
|
||||||
|
//
|
||||||
|
// Spaces at a break are dropped, each newline-separated paragraph wraps on
|
||||||
|
// its own, and leading indentation on a paragraph is kept. Only a word longer
|
||||||
|
// than a whole line is split, at the line edge.
|
||||||
|
func wrap(text string, first, width int) []string {
|
||||||
|
width = max(width, 1)
|
||||||
|
first = min(max(first, 0), width)
|
||||||
|
var lines []string
|
||||||
|
for i, para := range strings.Split(text, "\n") {
|
||||||
|
avail := width
|
||||||
|
if i == 0 {
|
||||||
|
avail = first
|
||||||
|
}
|
||||||
|
lines = append(lines, wrapParagraph([]rune(para), avail, width)...)
|
||||||
|
}
|
||||||
|
return lines
|
||||||
|
}
|
||||||
|
|
||||||
|
func wrapParagraph(para []rune, first, width int) []string {
|
||||||
|
var (
|
||||||
|
lines []string
|
||||||
|
line []rune
|
||||||
|
avail = first
|
||||||
|
// pending records a break point: spaces that did not fit were
|
||||||
|
// dropped, so the next word must start a new line.
|
||||||
|
pending bool
|
||||||
|
)
|
||||||
|
breakLine := func() {
|
||||||
|
lines = append(lines, string(trimTrailingSpaces(line)))
|
||||||
|
line = line[:0]
|
||||||
|
avail = width
|
||||||
|
pending = false
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tok := range tokenize(para) {
|
||||||
|
if tok[0] == ' ' {
|
||||||
|
switch {
|
||||||
|
case len(line) == 0 && len(lines) > 0:
|
||||||
|
// Spaces at the start of a wrapped line are dropped.
|
||||||
|
case !pending && len(line)+len(tok) <= avail:
|
||||||
|
line = append(line, tok...)
|
||||||
|
case len(line) > 0:
|
||||||
|
pending = true
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if pending {
|
||||||
|
breakLine()
|
||||||
|
}
|
||||||
|
if len(line)+len(tok) > avail {
|
||||||
|
if len(line) > 0 || avail < width {
|
||||||
|
breakLine()
|
||||||
|
}
|
||||||
|
for len(tok) > width {
|
||||||
|
line = append(line, tok[:width]...)
|
||||||
|
breakLine()
|
||||||
|
tok = tok[width:]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
line = append(line, tok...)
|
||||||
|
}
|
||||||
|
return append(lines, string(line))
|
||||||
|
}
|
||||||
|
|
||||||
|
// tokenize splits s into alternating runs of spaces and non-spaces.
|
||||||
|
func tokenize(s []rune) [][]rune {
|
||||||
|
var tokens [][]rune
|
||||||
|
start := 0
|
||||||
|
for i := 1; i <= len(s); i++ {
|
||||||
|
if i == len(s) || (s[i] == ' ') != (s[start] == ' ') {
|
||||||
|
tokens = append(tokens, s[start:i])
|
||||||
|
start = i
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return tokens
|
||||||
|
}
|
||||||
|
|
||||||
|
func trimTrailingSpaces(r []rune) []rune {
|
||||||
|
end := len(r)
|
||||||
|
for end > 0 && r[end-1] == ' ' {
|
||||||
|
end--
|
||||||
|
}
|
||||||
|
return r[:end]
|
||||||
|
}
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
package receipt
|
||||||
|
|
||||||
|
import (
|
||||||
|
"reflect"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestWrap(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
text string
|
||||||
|
first, width int
|
||||||
|
want []string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "fits", text: "hello world", first: 48, width: 48,
|
||||||
|
want: []string{"hello world"},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "breaks at word boundary", text: "the quick brown fox", first: 10, width: 10,
|
||||||
|
want: []string{"the quick", "brown fox"},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "never splits a word that fits on a line",
|
||||||
|
text: "Thank you for shopping with us today", first: 12, width: 12,
|
||||||
|
want: []string{"Thank you", "for shopping", "with us", "today"},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "hard splits only words longer than a line", text: "see https://example.com/very/long ok", first: 12, width: 12,
|
||||||
|
want: []string{"see", "https://exam", "ple.com/very", "/long ok"},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "runs of spaces kept inside a line", text: "a b", first: 10, width: 10,
|
||||||
|
want: []string{"a b"},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "spaces at a break are dropped", text: "aaaa b", first: 5, width: 5,
|
||||||
|
want: []string{"aaaa", "b"},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "paragraphs wrap independently", text: "one two\n\nthree", first: 5, width: 5,
|
||||||
|
want: []string{"one", "two", "", "three"},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "indent kept on first line only", text: " indented text here", first: 10, width: 10,
|
||||||
|
want: []string{" indented", "text here"},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "inline continuation fits", text: " world", first: 6, width: 10,
|
||||||
|
want: []string{" world"},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "inline continuation breaks before the word", text: "world", first: 3, width: 10,
|
||||||
|
want: []string{"", "world"},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "inline continuation keeps filling then wraps", text: " big wide world", first: 8, width: 10,
|
||||||
|
want: []string{" big", "wide world"},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "trailing space kept for inline use", text: "Total: ", first: 48, width: 48,
|
||||||
|
want: []string{"Total: "},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "empty", text: "", first: 10, width: 10,
|
||||||
|
want: []string{""},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "unicode counted as runes", text: "Grüße an Übermorgen", first: 10, width: 10,
|
||||||
|
want: []string{"Grüße an", "Übermorgen"},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
got := wrap(tt.text, tt.first, tt.width)
|
||||||
|
if !reflect.DeepEqual(got, tt.want) {
|
||||||
|
t.Errorf("wrap(%q, %d, %d) = %q, want %q", tt.text, tt.first, tt.width, got, tt.want)
|
||||||
|
}
|
||||||
|
for i, line := range got {
|
||||||
|
limit := tt.width
|
||||||
|
if i == 0 {
|
||||||
|
limit = tt.first
|
||||||
|
}
|
||||||
|
if n := len([]rune(line)); n > limit {
|
||||||
|
t.Errorf("line %d %q has %d runes, limit %d", i, line, n, limit)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestExpandTabs(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
in string
|
||||||
|
start int
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{"a\tb", 0, "a b"},
|
||||||
|
{"abcdefgh\tx", 0, "abcdefgh x"},
|
||||||
|
{"\tx", 3, " x"},
|
||||||
|
{"a\n\tb", 5, "a\n b"},
|
||||||
|
{"none", 0, "none"},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
if got := expandTabs(tt.in, tt.start); got != tt.want {
|
||||||
|
t.Errorf("expandTabs(%q, %d) = %q, want %q", tt.in, tt.start, got, tt.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSanitize(t *testing.T) {
|
||||||
|
if got := sanitize("a\x1b@b\r\n\tc\x00"); got != "a@b\n\tc" {
|
||||||
|
t.Errorf("sanitize = %q", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,359 @@
|
|||||||
|
package receipt_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/base64"
|
||||||
|
"errors"
|
||||||
|
"image"
|
||||||
|
"image/color"
|
||||||
|
"image/png"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/escpos"
|
||||||
|
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/receipt"
|
||||||
|
)
|
||||||
|
|
||||||
|
type fakeFetcher struct {
|
||||||
|
data []byte
|
||||||
|
err error
|
||||||
|
urls []string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fakeFetcher) Fetch(_ context.Context, url string) ([]byte, error) {
|
||||||
|
f.urls = append(f.urls, url)
|
||||||
|
return f.data, f.err
|
||||||
|
}
|
||||||
|
|
||||||
|
func newRenderer(t *testing.T, fetcher receipt.Fetcher) *receipt.Renderer {
|
||||||
|
t.Helper()
|
||||||
|
profile, err := escpos.LookupProfile("tm-t20")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return receipt.NewRenderer(receipt.Options{
|
||||||
|
Profile: profile,
|
||||||
|
CodePage: escpos.CodePage437,
|
||||||
|
MaxPixels: 10_000_000,
|
||||||
|
MaxHeight: 4000,
|
||||||
|
}, fetcher)
|
||||||
|
}
|
||||||
|
|
||||||
|
func pngData(t *testing.T, w, h int) []byte {
|
||||||
|
t.Helper()
|
||||||
|
img := image.NewGray(image.Rect(0, 0, w, h))
|
||||||
|
for i := range img.Pix {
|
||||||
|
img.Pix[i] = 0xFF
|
||||||
|
}
|
||||||
|
img.SetGray(0, 0, color.Gray{})
|
||||||
|
var buf bytes.Buffer
|
||||||
|
if err := png.Encode(&buf, img); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return buf.Bytes()
|
||||||
|
}
|
||||||
|
|
||||||
|
func boolPtr(b bool) *bool { return &b }
|
||||||
|
|
||||||
|
var (
|
||||||
|
initialize = []byte{0x1B, 0x40}
|
||||||
|
selectCP437 = []byte{0x1B, 0x74, 0}
|
||||||
|
partialCut = []byte{0x1D, 0x56, 66, 0}
|
||||||
|
sizeOne = []byte{0x1D, 0x21, 0x00}
|
||||||
|
sizeTwo = []byte{0x1D, 0x21, 0x11}
|
||||||
|
justifyLeft = []byte{0x1B, 0x61, 0}
|
||||||
|
justifyRight = []byte{0x1B, 0x61, 2}
|
||||||
|
)
|
||||||
|
|
||||||
|
func render(t *testing.T, job receipt.Job) []byte {
|
||||||
|
t.Helper()
|
||||||
|
out, err := newRenderer(t, &fakeFetcher{}).Render(context.Background(), job)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Render: %v", err)
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// printedLines returns the text the printer would print between line feeds,
|
||||||
|
// with ESC/POS commands removed. It understands only the commands the
|
||||||
|
// renderer emits for text jobs.
|
||||||
|
func printedLines(t *testing.T, out []byte) []string {
|
||||||
|
t.Helper()
|
||||||
|
var lines []string
|
||||||
|
var cur []byte
|
||||||
|
for i := 0; i < len(out); i++ {
|
||||||
|
switch c := out[i]; c {
|
||||||
|
case 0x1B: // ESC x n, or ESC @ / ESC 2
|
||||||
|
switch out[i+1] {
|
||||||
|
case '@', '2':
|
||||||
|
i++
|
||||||
|
default:
|
||||||
|
i += 2
|
||||||
|
}
|
||||||
|
case 0x1D: // GS x n, or GS V m n
|
||||||
|
if out[i+1] == 'V' {
|
||||||
|
i += 3
|
||||||
|
} else {
|
||||||
|
i += 2
|
||||||
|
}
|
||||||
|
case 0x0A:
|
||||||
|
lines = append(lines, string(cur))
|
||||||
|
cur = nil
|
||||||
|
default:
|
||||||
|
cur = append(cur, c)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(cur) > 0 {
|
||||||
|
lines = append(lines, string(cur))
|
||||||
|
}
|
||||||
|
return lines
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRenderTextJob(t *testing.T) {
|
||||||
|
out := render(t, receipt.Job{Elements: []receipt.Element{{Type: "text", Text: "Hi"}}})
|
||||||
|
if !bytes.HasPrefix(out, append(append([]byte{}, initialize...), selectCP437...)) {
|
||||||
|
t.Errorf("stream must start with ESC @ and ESC t 0, got % X", out[:min(5, len(out))])
|
||||||
|
}
|
||||||
|
if !bytes.HasSuffix(out, partialCut) {
|
||||||
|
t.Errorf("stream must end with a partial cut, got % X", out[len(out)-4:])
|
||||||
|
}
|
||||||
|
if got := printedLines(t, out); len(got) != 1 || got[0] != "Hi" {
|
||||||
|
t.Errorf("printed %q, want [\"Hi\"]", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRenderTranscodesToCodePage437(t *testing.T) {
|
||||||
|
out := render(t, receipt.Job{Elements: []receipt.Element{{Type: "text", Text: "┌─┐ Ü 🎉"}}})
|
||||||
|
if !bytes.Contains(out, []byte{0xDA, 0xC4, 0xBF, ' ', 0x9A, ' ', '?'}) {
|
||||||
|
t.Errorf("CP437 bytes not found in % X", out)
|
||||||
|
}
|
||||||
|
if bytes.Contains(out, []byte("┌")) {
|
||||||
|
t.Error("raw UTF-8 leaked into the stream")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRenderWrapsAtPaperWidth(t *testing.T) {
|
||||||
|
paragraph := strings.Repeat("lorem ipsum dolor sit amet ", 12)
|
||||||
|
out := render(t, receipt.Job{Elements: []receipt.Element{
|
||||||
|
{Type: "text", Text: paragraph},
|
||||||
|
{Type: "text", Text: paragraph, Size: 2},
|
||||||
|
}})
|
||||||
|
lines := printedLines(t, out)
|
||||||
|
if len(lines) < 4 {
|
||||||
|
t.Fatalf("expected wrapped output, got %q", lines)
|
||||||
|
}
|
||||||
|
words := map[string]bool{"lorem": true, "ipsum": true, "dolor": true, "sit": true, "amet": true}
|
||||||
|
for _, line := range lines {
|
||||||
|
if len(line) > 48 {
|
||||||
|
t.Errorf("line %q is %d chars, Font A size 1 fits 48", line, len(line))
|
||||||
|
}
|
||||||
|
for _, word := range strings.Fields(line) {
|
||||||
|
if !words[word] {
|
||||||
|
t.Errorf("word %q was split across lines", word)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sizeTwoStart := bytes.Index(out, sizeTwo)
|
||||||
|
for _, line := range printedLines(t, out[sizeTwoStart:]) {
|
||||||
|
if len(line) > 24 {
|
||||||
|
t.Errorf("size-2 line %q is %d chars, limit 24", line, len(line))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRenderInlineTextContinuesLine(t *testing.T) {
|
||||||
|
out := render(t, receipt.Job{Elements: []receipt.Element{
|
||||||
|
{Type: "text", Text: "Total: ", Newline: boolPtr(false)},
|
||||||
|
{Type: "text", Text: "£5.00", Bold: true},
|
||||||
|
}})
|
||||||
|
if got := printedLines(t, out); len(got) != 1 || got[0] != "Total: \x9C5.00" {
|
||||||
|
t.Errorf("printed %q, want one line", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRenderInlineMixedSizesWraps(t *testing.T) {
|
||||||
|
// 40 Font A columns used, then a size-2 word needing 2x6 = 12 columns:
|
||||||
|
// it cannot fit in the remaining 8 and must move to the next line.
|
||||||
|
out := render(t, receipt.Job{Elements: []receipt.Element{
|
||||||
|
{Type: "text", Text: strings.Repeat("x", 40), Newline: boolPtr(false)},
|
||||||
|
{Type: "text", Text: "BIGONE", Size: 2},
|
||||||
|
}})
|
||||||
|
lines := printedLines(t, out)
|
||||||
|
if len(lines) != 2 || lines[0] != strings.Repeat("x", 40) || lines[1] != "BIGONE" {
|
||||||
|
t.Errorf("printed %q", lines)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRenderNoWrap(t *testing.T) {
|
||||||
|
long := strings.Repeat("y", 60)
|
||||||
|
out := render(t, receipt.Job{Elements: []receipt.Element{{Type: "text", Text: long, Wrap: boolPtr(false)}}})
|
||||||
|
if got := printedLines(t, out); len(got) != 1 || got[0] != long {
|
||||||
|
t.Errorf("printed %q, want the text untouched", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRenderTextStyles(t *testing.T) {
|
||||||
|
out := render(t, receipt.Job{Elements: []receipt.Element{
|
||||||
|
{Type: "text", Text: "x", Bold: true, Underline: 2, Invert: true, Align: "right", Font: "b"},
|
||||||
|
}})
|
||||||
|
for name, cmd := range map[string][]byte{
|
||||||
|
"bold": {0x1B, 0x45, 1},
|
||||||
|
"underline": {0x1B, 0x2D, 2},
|
||||||
|
"reverse": {0x1D, 0x42, 1},
|
||||||
|
"font b": {0x1B, 0x4D, 1},
|
||||||
|
"right": justifyRight,
|
||||||
|
} {
|
||||||
|
if !bytes.Contains(out, cmd) {
|
||||||
|
t.Errorf("%s command % X missing", name, cmd)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Styles are reset after the element.
|
||||||
|
if !bytes.Contains(out, append([]byte{0x1B, 0x45, 0, 0x1B, 0x2D, 0, 0x1D, 0x42, 0}, sizeOne...)) {
|
||||||
|
t.Error("styles not reset after text")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRenderElements(t *testing.T) {
|
||||||
|
out := render(t, receipt.Job{Elements: []receipt.Element{
|
||||||
|
{Type: "feed", Lines: 3},
|
||||||
|
{Type: "qr", Data: "https://example.com", Align: "center"},
|
||||||
|
{Type: "barcode", Symbology: "code128", Data: "ABC-1"},
|
||||||
|
{Type: "raw", Hex: "1B 40"},
|
||||||
|
{Type: "cut", Mode: "full"},
|
||||||
|
}})
|
||||||
|
for name, cmd := range map[string][]byte{
|
||||||
|
"feed": {0x1B, 0x64, 3},
|
||||||
|
"qr store": append([]byte{0x1D, 0x28, 0x6B, 22, 0, 0x31, 0x50, 0x30}, "https://example.com"...),
|
||||||
|
"barcode": append([]byte{0x1D, 0x6B, 73, 7}, "{BABC-1"...),
|
||||||
|
"width": {0x1D, 0x77, 3},
|
||||||
|
"full cut": {0x1D, 0x56, 65, 0},
|
||||||
|
} {
|
||||||
|
if !bytes.Contains(out, cmd) {
|
||||||
|
t.Errorf("%s command % X missing", name, cmd)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if bytes.HasSuffix(out, partialCut) {
|
||||||
|
t.Error("an explicit final cut must not be followed by another")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRenderCopies(t *testing.T) {
|
||||||
|
out := render(t, receipt.Job{Copies: 3, Elements: []receipt.Element{{Type: "text", Text: "copy"}}})
|
||||||
|
if n := bytes.Count(out, partialCut); n != 3 {
|
||||||
|
t.Errorf("%d cuts, want 3", n)
|
||||||
|
}
|
||||||
|
if n := bytes.Count(out, initialize); n != 1 {
|
||||||
|
t.Errorf("%d initialize commands, want 1", n)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRenderBase64ImageCentered(t *testing.T) {
|
||||||
|
data := base64.StdEncoding.EncodeToString(pngData(t, 100, 10))
|
||||||
|
out := render(t, receipt.Job{Elements: []receipt.Element{{Type: "image", Base64: data, Align: "center"}}})
|
||||||
|
// The image is placed on a full-width 576-dot (72-byte) canvas.
|
||||||
|
header := []byte{0x1D, 0x76, 0x30, 0, 72, 0, 10, 0}
|
||||||
|
i := bytes.Index(out, header)
|
||||||
|
if i < 0 {
|
||||||
|
t.Fatalf("raster header % X not found", header)
|
||||||
|
}
|
||||||
|
if !bytes.Contains(out[:i], justifyLeft) {
|
||||||
|
t.Error("image must be sent left-justified; alignment is in the bitmap")
|
||||||
|
}
|
||||||
|
// The dark pixel at x=0 lands at x=(576-100)/2=238: byte 29, bit 6.
|
||||||
|
if got := out[i+8+29]; got != 0x02 {
|
||||||
|
t.Errorf("first row byte 29 = %08b, want 00000010", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRenderImageFromURL(t *testing.T) {
|
||||||
|
fetcher := &fakeFetcher{data: pngData(t, 1200, 300)}
|
||||||
|
out, err := newRenderer(t, fetcher).Render(context.Background(), receipt.Job{Elements: []receipt.Element{
|
||||||
|
{Type: "image", URL: "https://images.example/logo.png"},
|
||||||
|
}})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(fetcher.urls) != 1 || fetcher.urls[0] != "https://images.example/logo.png" {
|
||||||
|
t.Errorf("fetched %v", fetcher.urls)
|
||||||
|
}
|
||||||
|
// Scaled down to 576 dots wide, 144 tall.
|
||||||
|
if !bytes.Contains(out, []byte{0x1D, 0x76, 0x30, 0, 72, 0, 144, 0}) {
|
||||||
|
t.Error("scaled raster header not found")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRenderFetchFailureProducesNothing(t *testing.T) {
|
||||||
|
fetchErr := errors.New("blocked")
|
||||||
|
out, err := newRenderer(t, &fakeFetcher{err: fetchErr}).Render(context.Background(), receipt.Job{Elements: []receipt.Element{
|
||||||
|
{Type: "text", Text: "before"},
|
||||||
|
{Type: "image", URL: "https://images.example/x.png"},
|
||||||
|
}})
|
||||||
|
if !errors.Is(err, fetchErr) || out != nil {
|
||||||
|
t.Errorf("Render = %d bytes, %v; want nil and the fetch error", len(out), err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestValidate(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
job receipt.Job
|
||||||
|
wantErr string
|
||||||
|
}{
|
||||||
|
{"no elements", receipt.Job{}, "at least one element"},
|
||||||
|
{"too many copies", receipt.Job{Copies: 6, Elements: []receipt.Element{{Type: "cut"}}}, "copies must be 1-5"},
|
||||||
|
{"missing type", receipt.Job{Elements: []receipt.Element{{}}}, "type is required"},
|
||||||
|
{"unknown type", receipt.Job{Elements: []receipt.Element{{Type: "sparkle"}}}, `unknown type "sparkle"`},
|
||||||
|
{"text size", receipt.Job{Elements: []receipt.Element{{Type: "text", Size: 9}}}, "elements[0] (text): size, width and height must be 1-8"},
|
||||||
|
{"text align", receipt.Job{Elements: []receipt.Element{{Type: "text", Align: "middle"}}}, "align must be left, center or right"},
|
||||||
|
{"text font", receipt.Job{Elements: []receipt.Element{{Type: "text", Font: "c"}}}, "font must be a or b"},
|
||||||
|
{"underline", receipt.Job{Elements: []receipt.Element{{Type: "text", Underline: 3}}}, "underline must be 0, 1 or 2"},
|
||||||
|
{"feed lines", receipt.Job{Elements: []receipt.Element{{Type: "feed", Lines: 300}}}, "lines must be 1-255"},
|
||||||
|
{"qr data", receipt.Job{Elements: []receipt.Element{{Type: "qr"}}}, "data is required"},
|
||||||
|
{"qr size", receipt.Job{Elements: []receipt.Element{{Type: "qr", Data: "x", Size: 17}}}, "size must be 1-16"},
|
||||||
|
{"qr correction", receipt.Job{Elements: []receipt.Element{{Type: "qr", Data: "x", Correction: "Z"}}}, "correction must be L, M, Q or H"},
|
||||||
|
{"barcode symbology", receipt.Job{Elements: []receipt.Element{{Type: "barcode", Data: "1"}}}, "symbology is required"},
|
||||||
|
{"barcode data", receipt.Job{Elements: []receipt.Element{{Type: "barcode", Symbology: "ean13", Data: "12"}}}, "want 12 or 13 digits"},
|
||||||
|
{"barcode width", receipt.Job{Elements: []receipt.Element{{Type: "barcode", Symbology: "code39", Data: "A", Width: 9}}}, "width must be 2-6"},
|
||||||
|
{"image source", receipt.Job{Elements: []receipt.Element{{Type: "image"}}}, "url or base64 is required"},
|
||||||
|
{"image both", receipt.Job{Elements: []receipt.Element{{Type: "image", URL: "https://x/y", Base64: "AA=="}}}, "not both"},
|
||||||
|
{"image scheme", receipt.Job{Elements: []receipt.Element{{Type: "image", URL: "file:///etc/passwd"}}}, "http or https"},
|
||||||
|
{"image base64", receipt.Job{Elements: []receipt.Element{{Type: "image", Base64: "!!!"}}}, "not valid base64"},
|
||||||
|
{"raw hex", receipt.Job{Elements: []receipt.Element{{Type: "raw", Hex: "zz"}}}, "hex:"},
|
||||||
|
{"cut mode", receipt.Job{Elements: []receipt.Element{{Type: "cut", Mode: "half"}}}, "mode must be partial or full"},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
err := tt.job.Validate()
|
||||||
|
var ve *receipt.ValidationError
|
||||||
|
if !errors.As(err, &ve) {
|
||||||
|
t.Fatalf("err = %v, want *ValidationError", err)
|
||||||
|
}
|
||||||
|
if !strings.Contains(err.Error(), tt.wantErr) {
|
||||||
|
t.Errorf("err = %q, want it to contain %q", err, tt.wantErr)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestValidateReportsEveryProblem(t *testing.T) {
|
||||||
|
err := receipt.Job{Elements: []receipt.Element{
|
||||||
|
{Type: "text", Size: 0},
|
||||||
|
{Type: "feed", Lines: -1},
|
||||||
|
{Type: "qr"},
|
||||||
|
}}.Validate()
|
||||||
|
var ve *receipt.ValidationError
|
||||||
|
if !errors.As(err, &ve) || len(ve.Problems) != 2 {
|
||||||
|
t.Fatalf("problems = %v, want 2 (feed and qr)", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestValidateAcceptsDataURI(t *testing.T) {
|
||||||
|
job := receipt.Job{Elements: []receipt.Element{{
|
||||||
|
Type: "image",
|
||||||
|
Base64: "data:image/png;base64," + base64.StdEncoding.EncodeToString([]byte("x")),
|
||||||
|
}}}
|
||||||
|
if err := job.Validate(); err != nil {
|
||||||
|
t.Errorf("Validate: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,295 @@
|
|||||||
|
package receipt
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"image"
|
||||||
|
"strings"
|
||||||
|
"unicode/utf8"
|
||||||
|
|
||||||
|
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/escpos"
|
||||||
|
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/raster"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Fetcher downloads remote image data.
|
||||||
|
type Fetcher interface {
|
||||||
|
Fetch(ctx context.Context, url string) ([]byte, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Options configures a Renderer.
|
||||||
|
type Options struct {
|
||||||
|
// Profile describes the printer; its DotsPerLine is the image width.
|
||||||
|
Profile escpos.Profile
|
||||||
|
|
||||||
|
// CodePage is the character table text is transcoded to.
|
||||||
|
CodePage escpos.CodePage
|
||||||
|
|
||||||
|
// Columns, when positive, overrides the Font A characters per line used
|
||||||
|
// for word wrapping.
|
||||||
|
Columns int
|
||||||
|
|
||||||
|
// MaxPixels caps decoded image size; MaxHeight caps printed image height
|
||||||
|
// in dots.
|
||||||
|
MaxPixels int
|
||||||
|
MaxHeight int
|
||||||
|
}
|
||||||
|
|
||||||
|
// Renderer turns jobs into ESC/POS command streams. It is safe for concurrent
|
||||||
|
// use.
|
||||||
|
type Renderer struct {
|
||||||
|
options Options
|
||||||
|
fetcher Fetcher
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewRenderer returns a Renderer. fetcher loads images given by URL.
|
||||||
|
func NewRenderer(options Options, fetcher Fetcher) *Renderer {
|
||||||
|
if fetcher == nil {
|
||||||
|
panic("receipt.NewRenderer: fetcher must not be nil")
|
||||||
|
}
|
||||||
|
if options.Profile.DotsPerLine <= 0 || options.Profile.FontAWidth <= 0 || options.Profile.FontBWidth <= 0 {
|
||||||
|
panic("receipt.NewRenderer: profile must be set")
|
||||||
|
}
|
||||||
|
if options.MaxPixels <= 0 || options.MaxHeight <= 0 {
|
||||||
|
panic("receipt.NewRenderer: image limits must be positive")
|
||||||
|
}
|
||||||
|
return &Renderer{options: options, fetcher: fetcher}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Render validates job, loads its images and returns the complete command
|
||||||
|
// stream. Nothing is returned unless the whole receipt rendered, so a failure
|
||||||
|
// never reaches the printer half-done.
|
||||||
|
func (r *Renderer) Render(ctx context.Context, job Job) ([]byte, error) {
|
||||||
|
if err := job.Validate(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
images, err := r.loadImages(ctx, job)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var body escpos.Builder
|
||||||
|
p := printer{b: &body, lineDots: r.textLineDots(), profile: r.options.Profile, codePage: r.options.CodePage}
|
||||||
|
for i, el := range job.Elements {
|
||||||
|
if err := p.element(el, images[i]); err != nil {
|
||||||
|
return nil, fmt.Errorf("rendering elements[%d] (%s): %w", i, el.Type, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
p.endLine()
|
||||||
|
if last := job.Elements[len(job.Elements)-1]; last.Type != TypeCut {
|
||||||
|
body.Cut(escpos.CutPartial, 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
var out escpos.Builder
|
||||||
|
out.Initialize()
|
||||||
|
out.SelectCodePage(r.options.CodePage)
|
||||||
|
for range job.copies() {
|
||||||
|
out.Raw(body.Bytes())
|
||||||
|
}
|
||||||
|
return bytes.Clone(out.Bytes()), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// textLineDots is the line width used for text layout.
|
||||||
|
func (r *Renderer) textLineDots() int {
|
||||||
|
if r.options.Columns > 0 {
|
||||||
|
return r.options.Columns * r.options.Profile.FontAWidth
|
||||||
|
}
|
||||||
|
return r.options.Profile.DotsPerLine
|
||||||
|
}
|
||||||
|
|
||||||
|
// loadImages fetches, decodes and dithers every image before anything is
|
||||||
|
// rendered, keyed by element index.
|
||||||
|
func (r *Renderer) loadImages(ctx context.Context, job Job) (map[int]*image.Paletted, error) {
|
||||||
|
images := make(map[int]*image.Paletted)
|
||||||
|
for i, el := range job.Elements {
|
||||||
|
if el.Type != TypeImage {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
img, err := r.loadImage(ctx, el)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("elements[%d] (image): %w", i, err)
|
||||||
|
}
|
||||||
|
images[i] = img
|
||||||
|
}
|
||||||
|
return images, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Renderer) loadImage(ctx context.Context, el Element) (*image.Paletted, error) {
|
||||||
|
spec, err := el.imageSpec()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
data := spec.data
|
||||||
|
if spec.url != "" {
|
||||||
|
if data, err = r.fetcher.Fetch(ctx, spec.url); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
src, err := raster.Decode(data, r.options.MaxPixels)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
paper := r.options.Profile.DotsPerLine
|
||||||
|
width := min(src.Bounds().Dx(), paper)
|
||||||
|
if spec.width > 0 {
|
||||||
|
if spec.width > paper {
|
||||||
|
return nil, fmt.Errorf("width %d is wider than the %d-dot paper", spec.width, paper)
|
||||||
|
}
|
||||||
|
width = spec.width
|
||||||
|
}
|
||||||
|
mono, err := raster.Monochrome(src, width)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if h := mono.Bounds().Dy(); h > r.options.MaxHeight {
|
||||||
|
return nil, fmt.Errorf("image is %d dots tall after scaling, limit is %d", h, r.options.MaxHeight)
|
||||||
|
}
|
||||||
|
|
||||||
|
var x int
|
||||||
|
switch spec.align {
|
||||||
|
case escpos.JustifyCenter:
|
||||||
|
x = (paper - width) / 2
|
||||||
|
case escpos.JustifyRight:
|
||||||
|
x = paper - width
|
||||||
|
}
|
||||||
|
return raster.Place(mono, paper, x)
|
||||||
|
}
|
||||||
|
|
||||||
|
// printer writes elements to a Builder while tracking the horizontal print
|
||||||
|
// position, in dots, so inline text can continue and wrap across elements.
|
||||||
|
type printer struct {
|
||||||
|
b *escpos.Builder
|
||||||
|
lineDots int
|
||||||
|
profile escpos.Profile
|
||||||
|
codePage escpos.CodePage
|
||||||
|
x int
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *printer) element(el Element, img *image.Paletted) error {
|
||||||
|
switch el.Type {
|
||||||
|
case TypeText:
|
||||||
|
return p.text(el)
|
||||||
|
case TypeFeed:
|
||||||
|
lines, err := el.feedLines()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
p.b.Feed(lines)
|
||||||
|
p.x = 0
|
||||||
|
case TypeQR:
|
||||||
|
spec, err := el.qrSpec()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
p.endLine()
|
||||||
|
p.b.Justify(spec.align)
|
||||||
|
return p.b.QRCode([]byte(el.Data), spec.size, spec.correction)
|
||||||
|
case TypeBarcode:
|
||||||
|
spec, err := el.barcodeSpec()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
p.endLine()
|
||||||
|
p.b.Justify(spec.align)
|
||||||
|
p.b.BarcodeHeight(uint8(spec.height))
|
||||||
|
if err := p.b.BarcodeWidth(spec.width); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
p.b.BarcodeHRI(spec.hri)
|
||||||
|
return p.b.Barcode(spec.symbology, el.Data)
|
||||||
|
case TypeImage:
|
||||||
|
p.endLine()
|
||||||
|
// Alignment is baked into the image; see Renderer.loadImage.
|
||||||
|
p.b.Justify(escpos.JustifyLeft)
|
||||||
|
return p.b.RasterImage(img)
|
||||||
|
case TypeRaw:
|
||||||
|
data, err := el.rawBytes()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
p.b.Raw(data)
|
||||||
|
// The position after arbitrary bytes is unknown; assume a fresh line.
|
||||||
|
p.x = 0
|
||||||
|
case TypeCut:
|
||||||
|
mode, err := el.cutMode()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
p.endLine()
|
||||||
|
p.b.Cut(mode, 0)
|
||||||
|
default:
|
||||||
|
return fmt.Errorf("unknown type %q", el.Type)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *printer) text(el Element) error {
|
||||||
|
spec, err := el.textSpec()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
glyph := p.profile.GlyphWidth(spec.font) * spec.width
|
||||||
|
|
||||||
|
p.b.Justify(spec.align)
|
||||||
|
p.b.Font(spec.font)
|
||||||
|
if err := p.b.Size(spec.width, spec.height); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
p.b.Bold(spec.bold)
|
||||||
|
p.b.Underline(spec.underline)
|
||||||
|
p.b.Reverse(spec.invert)
|
||||||
|
|
||||||
|
text := sanitize(el.Text)
|
||||||
|
if spec.wrap {
|
||||||
|
text = expandTabs(text, p.x/glyph)
|
||||||
|
lines := wrap(text, (p.lineDots-p.x)/glyph, p.lineDots/glyph)
|
||||||
|
for i, line := range lines {
|
||||||
|
if i > 0 {
|
||||||
|
p.b.LineFeed()
|
||||||
|
p.x = 0
|
||||||
|
}
|
||||||
|
p.b.Text(p.codePage.Encode(line))
|
||||||
|
p.x += utf8.RuneCountInString(line) * glyph
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
p.b.Text(p.codePage.Encode(text))
|
||||||
|
p.advance(text, glyph)
|
||||||
|
}
|
||||||
|
if spec.newline {
|
||||||
|
p.b.LineFeed()
|
||||||
|
p.x = 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reset styles so they cannot leak into barcodes, QR codes or raw data.
|
||||||
|
p.b.Bold(false)
|
||||||
|
p.b.Underline(escpos.UnderlineNone)
|
||||||
|
p.b.Reverse(false)
|
||||||
|
if err := p.b.Size(1, 1); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
p.b.Font(escpos.FontA)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// advance updates the position after unwrapped text, which the printer wraps
|
||||||
|
// by itself when it overflows.
|
||||||
|
func (p *printer) advance(text string, glyph int) {
|
||||||
|
if i := strings.LastIndexByte(text, '\n'); i >= 0 {
|
||||||
|
p.x = 0
|
||||||
|
text = text[i+1:]
|
||||||
|
}
|
||||||
|
p.x += utf8.RuneCountInString(text) * glyph
|
||||||
|
if p.lineDots > 0 {
|
||||||
|
p.x %= p.lineDots
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// endLine finishes a partially printed line so the next element starts at
|
||||||
|
// the left margin.
|
||||||
|
func (p *printer) endLine() {
|
||||||
|
if p.x > 0 {
|
||||||
|
p.b.LineFeed()
|
||||||
|
p.x = 0
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,216 @@
|
|||||||
|
// Package safehttp fetches remote resources on behalf of API clients while
|
||||||
|
// refusing to connect to internal network addresses, which guards against
|
||||||
|
// server-side request forgery (SSRF).
|
||||||
|
//
|
||||||
|
// Addresses are checked at dial time, after DNS resolution, so a hostname that
|
||||||
|
// resolves (or re-resolves) to a private address is refused too.
|
||||||
|
package safehttp
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"net/netip"
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
"syscall"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// maxRedirects bounds redirect chains.
|
||||||
|
const maxRedirects = 5
|
||||||
|
|
||||||
|
var (
|
||||||
|
// ErrBlockedAddress is returned when a destination resolves to an address
|
||||||
|
// that is not allowed.
|
||||||
|
ErrBlockedAddress = errors.New("safehttp: destination address is not allowed")
|
||||||
|
|
||||||
|
// ErrHostNotAllowed is returned when an allowlist is configured and the
|
||||||
|
// host is not on it.
|
||||||
|
ErrHostNotAllowed = errors.New("safehttp: host is not on the allowlist")
|
||||||
|
|
||||||
|
// ErrScheme is returned for URLs that are not http or https.
|
||||||
|
ErrScheme = errors.New("safehttp: only http and https URLs are allowed")
|
||||||
|
|
||||||
|
// ErrTooLarge is returned when a response body exceeds the size limit.
|
||||||
|
ErrTooLarge = errors.New("safehttp: response exceeds size limit")
|
||||||
|
)
|
||||||
|
|
||||||
|
// Options configures a Client.
|
||||||
|
type Options struct {
|
||||||
|
// Timeout bounds a whole fetch, including redirects and reading the body.
|
||||||
|
Timeout time.Duration
|
||||||
|
|
||||||
|
// MaxBytes is the largest response body accepted.
|
||||||
|
MaxBytes int64
|
||||||
|
|
||||||
|
// AllowPrivate permits loopback, private, link-local and other
|
||||||
|
// non-public destinations.
|
||||||
|
AllowPrivate bool
|
||||||
|
|
||||||
|
// AllowedHosts, when non-empty, restricts fetches to these hostnames.
|
||||||
|
// Listed hosts may resolve to private addresses.
|
||||||
|
AllowedHosts []string
|
||||||
|
}
|
||||||
|
|
||||||
|
// Client fetches URLs with SSRF protection. It is safe for concurrent use.
|
||||||
|
type Client struct {
|
||||||
|
http *http.Client
|
||||||
|
maxBytes int64
|
||||||
|
allowPrivate bool
|
||||||
|
allowed map[string]struct{}
|
||||||
|
}
|
||||||
|
|
||||||
|
// New returns a Client configured by o.
|
||||||
|
func New(o Options) *Client {
|
||||||
|
c := &Client{
|
||||||
|
maxBytes: o.MaxBytes,
|
||||||
|
allowPrivate: o.AllowPrivate,
|
||||||
|
allowed: make(map[string]struct{}, len(o.AllowedHosts)),
|
||||||
|
}
|
||||||
|
for _, host := range o.AllowedHosts {
|
||||||
|
c.allowed[strings.ToLower(host)] = struct{}{}
|
||||||
|
}
|
||||||
|
|
||||||
|
guarded := &net.Dialer{Timeout: o.Timeout, Control: c.checkDialAddress}
|
||||||
|
plain := &net.Dialer{Timeout: o.Timeout}
|
||||||
|
transport := &http.Transport{
|
||||||
|
// No proxy: a proxy would make the dial-time address check useless.
|
||||||
|
Proxy: nil,
|
||||||
|
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||||
|
host, _, err := net.SplitHostPort(addr)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if c.allowlisted(host) {
|
||||||
|
return plain.DialContext(ctx, network, addr)
|
||||||
|
}
|
||||||
|
return guarded.DialContext(ctx, network, addr)
|
||||||
|
},
|
||||||
|
ForceAttemptHTTP2: true,
|
||||||
|
MaxIdleConns: 10,
|
||||||
|
IdleConnTimeout: 30 * time.Second,
|
||||||
|
TLSHandshakeTimeout: o.Timeout,
|
||||||
|
ResponseHeaderTimeout: o.Timeout,
|
||||||
|
}
|
||||||
|
c.http = &http.Client{
|
||||||
|
Transport: transport,
|
||||||
|
Timeout: o.Timeout,
|
||||||
|
CheckRedirect: func(req *http.Request, via []*http.Request) error {
|
||||||
|
if len(via) >= maxRedirects {
|
||||||
|
return fmt.Errorf("safehttp: stopped after %d redirects", maxRedirects)
|
||||||
|
}
|
||||||
|
return c.checkURL(req.URL)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
return c
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fetch GETs rawURL and returns the response body.
|
||||||
|
func (c *Client) Fetch(ctx context.Context, rawURL string) ([]byte, error) {
|
||||||
|
u, err := url.Parse(rawURL)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("parsing URL: %w", err)
|
||||||
|
}
|
||||||
|
if err := c.checkURL(u); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("building request: %w", err)
|
||||||
|
}
|
||||||
|
req.Header.Set("User-Agent", "uberbringer")
|
||||||
|
resp, err := c.http.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("fetching %s: %w", u.Redacted(), err)
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
if resp.StatusCode != http.StatusOK {
|
||||||
|
return nil, fmt.Errorf("fetching %s: unexpected status %s", u.Redacted(), resp.Status)
|
||||||
|
}
|
||||||
|
if resp.ContentLength > c.maxBytes {
|
||||||
|
return nil, fmt.Errorf("%w: %d bytes, limit is %d", ErrTooLarge, resp.ContentLength, c.maxBytes)
|
||||||
|
}
|
||||||
|
body, err := io.ReadAll(io.LimitReader(resp.Body, c.maxBytes+1))
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("reading %s: %w", u.Redacted(), err)
|
||||||
|
}
|
||||||
|
if int64(len(body)) > c.maxBytes {
|
||||||
|
return nil, fmt.Errorf("%w: limit is %d bytes", ErrTooLarge, c.maxBytes)
|
||||||
|
}
|
||||||
|
return body, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// checkURL validates the scheme and, when an allowlist is set, the host.
|
||||||
|
func (c *Client) checkURL(u *url.URL) error {
|
||||||
|
if u.Scheme != "http" && u.Scheme != "https" {
|
||||||
|
return fmt.Errorf("%w: %q", ErrScheme, u.Scheme)
|
||||||
|
}
|
||||||
|
if u.Hostname() == "" {
|
||||||
|
return fmt.Errorf("safehttp: URL has no host")
|
||||||
|
}
|
||||||
|
if len(c.allowed) > 0 && !c.allowlisted(u.Hostname()) {
|
||||||
|
return fmt.Errorf("%w: %s", ErrHostNotAllowed, u.Hostname())
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) allowlisted(host string) bool {
|
||||||
|
_, ok := c.allowed[strings.ToLower(host)]
|
||||||
|
return ok
|
||||||
|
}
|
||||||
|
|
||||||
|
// checkDialAddress runs after DNS resolution with the concrete IP the dialer
|
||||||
|
// is about to connect to.
|
||||||
|
func (c *Client) checkDialAddress(_, address string, _ syscall.RawConn) error {
|
||||||
|
if c.allowPrivate {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
addrPort, err := netip.ParseAddrPort(address)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("%w: %s", ErrBlockedAddress, address)
|
||||||
|
}
|
||||||
|
if !IsPublic(addrPort.Addr()) {
|
||||||
|
return fmt.Errorf("%w: %s", ErrBlockedAddress, addrPort.Addr())
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// nonPublic lists ranges that are not reachable on the public internet and
|
||||||
|
// are not already covered by the netip.Addr predicates in IsPublic. It is
|
||||||
|
// effectively constant and must not be modified.
|
||||||
|
var nonPublic = []netip.Prefix{
|
||||||
|
netip.MustParsePrefix("0.0.0.0/8"), // "this" network
|
||||||
|
netip.MustParsePrefix("100.64.0.0/10"), // carrier-grade NAT
|
||||||
|
netip.MustParsePrefix("192.0.0.0/24"), // IETF protocol assignments
|
||||||
|
netip.MustParsePrefix("192.0.2.0/24"), // TEST-NET-1
|
||||||
|
netip.MustParsePrefix("198.18.0.0/15"), // benchmarking
|
||||||
|
netip.MustParsePrefix("198.51.100.0/24"), // TEST-NET-2
|
||||||
|
netip.MustParsePrefix("203.0.113.0/24"), // TEST-NET-3
|
||||||
|
netip.MustParsePrefix("240.0.0.0/4"), // reserved, includes broadcast
|
||||||
|
netip.MustParsePrefix("2001:db8::/32"), // documentation
|
||||||
|
netip.MustParsePrefix("64:ff9b:1::/48"), // local-use NAT64
|
||||||
|
}
|
||||||
|
|
||||||
|
// IsPublic reports whether addr is a globally routable unicast address.
|
||||||
|
// Loopback, private (RFC 1918 and IPv6 ULA), link-local (which includes cloud
|
||||||
|
// metadata endpoints), multicast and reserved ranges are not public.
|
||||||
|
func IsPublic(addr netip.Addr) bool {
|
||||||
|
addr = addr.Unmap()
|
||||||
|
if !addr.IsValid() || addr.IsLoopback() || addr.IsPrivate() || addr.IsUnspecified() ||
|
||||||
|
addr.IsLinkLocalUnicast() || addr.IsLinkLocalMulticast() ||
|
||||||
|
addr.IsInterfaceLocalMulticast() || addr.IsMulticast() {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for _, prefix := range nonPublic {
|
||||||
|
if prefix.Contains(addr) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
@@ -0,0 +1,150 @@
|
|||||||
|
package safehttp_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"net/netip"
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/safehttp"
|
||||||
|
)
|
||||||
|
|
||||||
|
func newServer(t *testing.T, body string) *httptest.Server {
|
||||||
|
t.Helper()
|
||||||
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||||
|
_, _ = w.Write([]byte(body)) // test server; the client side asserts the outcome
|
||||||
|
}))
|
||||||
|
t.Cleanup(srv.Close)
|
||||||
|
return srv
|
||||||
|
}
|
||||||
|
|
||||||
|
func options() safehttp.Options {
|
||||||
|
return safehttp.Options{Timeout: 5 * time.Second, MaxBytes: 1 << 20}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFetchBlocksLoopbackByDefault(t *testing.T) {
|
||||||
|
srv := newServer(t, "secret")
|
||||||
|
_, err := safehttp.New(options()).Fetch(context.Background(), srv.URL)
|
||||||
|
if !errors.Is(err, safehttp.ErrBlockedAddress) {
|
||||||
|
t.Fatalf("err = %v, want ErrBlockedAddress", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFetchBlocksHostnameResolvingToLoopback(t *testing.T) {
|
||||||
|
srv := newServer(t, "secret")
|
||||||
|
u, _ := url.Parse(srv.URL)
|
||||||
|
u.Host = "localhost:" + u.Port()
|
||||||
|
_, err := safehttp.New(options()).Fetch(context.Background(), u.String())
|
||||||
|
if !errors.Is(err, safehttp.ErrBlockedAddress) {
|
||||||
|
t.Fatalf("err = %v, want ErrBlockedAddress", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFetchAllowPrivate(t *testing.T) {
|
||||||
|
srv := newServer(t, "hello")
|
||||||
|
o := options()
|
||||||
|
o.AllowPrivate = true
|
||||||
|
body, err := safehttp.New(o).Fetch(context.Background(), srv.URL)
|
||||||
|
if err != nil || string(body) != "hello" {
|
||||||
|
t.Fatalf("Fetch = %q, %v", body, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFetchAllowlistedHostMayBePrivate(t *testing.T) {
|
||||||
|
srv := newServer(t, "hello")
|
||||||
|
o := options()
|
||||||
|
o.AllowedHosts = []string{"127.0.0.1"}
|
||||||
|
body, err := safehttp.New(o).Fetch(context.Background(), srv.URL)
|
||||||
|
if err != nil || string(body) != "hello" {
|
||||||
|
t.Fatalf("Fetch = %q, %v", body, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFetchAllowlistRejectsOtherHosts(t *testing.T) {
|
||||||
|
o := options()
|
||||||
|
o.AllowedHosts = []string{"images.example"}
|
||||||
|
_, err := safehttp.New(o).Fetch(context.Background(), "https://evil.example/x.png")
|
||||||
|
if !errors.Is(err, safehttp.ErrHostNotAllowed) {
|
||||||
|
t.Fatalf("err = %v, want ErrHostNotAllowed", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFetchRedirectToOtherHostIsChecked(t *testing.T) {
|
||||||
|
target := newServer(t, "internal")
|
||||||
|
targetURL, _ := url.Parse(target.URL)
|
||||||
|
// The allowlisted redirector sends the client to "localhost", which is
|
||||||
|
// not on the allowlist, so the redirect must be refused.
|
||||||
|
redirector := httptest.NewServer(http.RedirectHandler("http://localhost:"+targetURL.Port(), http.StatusFound))
|
||||||
|
t.Cleanup(redirector.Close)
|
||||||
|
|
||||||
|
o := options()
|
||||||
|
o.AllowedHosts = []string{"127.0.0.1"}
|
||||||
|
_, err := safehttp.New(o).Fetch(context.Background(), redirector.URL)
|
||||||
|
if !errors.Is(err, safehttp.ErrHostNotAllowed) {
|
||||||
|
t.Fatalf("err = %v, want ErrHostNotAllowed", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFetchRejectsSchemes(t *testing.T) {
|
||||||
|
for _, raw := range []string{"file:///etc/passwd", "ftp://example.com/x", "gopher://x"} {
|
||||||
|
_, err := safehttp.New(options()).Fetch(context.Background(), raw)
|
||||||
|
if !errors.Is(err, safehttp.ErrScheme) {
|
||||||
|
t.Errorf("Fetch(%q) err = %v, want ErrScheme", raw, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFetchSizeLimit(t *testing.T) {
|
||||||
|
srv := newServer(t, strings.Repeat("x", 2048))
|
||||||
|
o := options()
|
||||||
|
o.AllowPrivate = true
|
||||||
|
o.MaxBytes = 1024
|
||||||
|
_, err := safehttp.New(o).Fetch(context.Background(), srv.URL)
|
||||||
|
if !errors.Is(err, safehttp.ErrTooLarge) {
|
||||||
|
t.Fatalf("err = %v, want ErrTooLarge", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFetchNon200(t *testing.T) {
|
||||||
|
srv := httptest.NewServer(http.NotFoundHandler())
|
||||||
|
t.Cleanup(srv.Close)
|
||||||
|
o := options()
|
||||||
|
o.AllowPrivate = true
|
||||||
|
if _, err := safehttp.New(o).Fetch(context.Background(), srv.URL); err == nil {
|
||||||
|
t.Fatal("expected error for 404")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestIsPublic(t *testing.T) {
|
||||||
|
tests := map[string]bool{
|
||||||
|
"8.8.8.8": true,
|
||||||
|
"1.1.1.1": true,
|
||||||
|
"2606:4700::1111": true,
|
||||||
|
"127.0.0.1": false,
|
||||||
|
"10.1.2.3": false,
|
||||||
|
"172.16.0.1": false,
|
||||||
|
"192.168.1.245": false,
|
||||||
|
"169.254.169.254": false, // cloud metadata
|
||||||
|
"100.64.0.1": false,
|
||||||
|
"0.0.0.0": false,
|
||||||
|
"255.255.255.255": false,
|
||||||
|
"::1": false,
|
||||||
|
"fd00::1": false,
|
||||||
|
"fe80::1": false,
|
||||||
|
"::ffff:127.0.0.1": false, // IPv4-mapped loopback
|
||||||
|
"::ffff:192.168.0.1": false,
|
||||||
|
"224.0.0.1": false,
|
||||||
|
"2001:db8::1": false,
|
||||||
|
"::ffff:93.184.216.34": true,
|
||||||
|
}
|
||||||
|
for raw, want := range tests {
|
||||||
|
if got := safehttp.IsPublic(netip.MustParseAddr(raw)); got != want {
|
||||||
|
t.Errorf("IsPublic(%s) = %v, want %v", raw, got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,134 +0,0 @@
|
|||||||
package service
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/hex"
|
|
||||||
fifo "github.com/foize/go.fifo"
|
|
||||||
"github.com/justinmichaelvieira/escpos"
|
|
||||||
"github.com/liamg/tml"
|
|
||||||
"image"
|
|
||||||
"net"
|
|
||||||
"net/http"
|
|
||||||
"uberbringer/config"
|
|
||||||
|
|
||||||
_ "image/jpeg"
|
|
||||||
_ "image/png"
|
|
||||||
)
|
|
||||||
|
|
||||||
func newPrintJob(input DataStruct, queue *fifo.Queue) {
|
|
||||||
var byteLength int
|
|
||||||
|
|
||||||
for _, item := range input.Data {
|
|
||||||
byteLength += len(item.Text)
|
|
||||||
}
|
|
||||||
|
|
||||||
if byteLength > 4096 {
|
|
||||||
tml.Printf("<red>[" + config.Project + "]: Job #" + input.JobID + " buffer limit reached</red>\n")
|
|
||||||
return
|
|
||||||
} else {
|
|
||||||
tml.Printf("<blue>[" + config.Project + "]: Job #" + input.JobID + " buffer size used " + string(byteLength) + " bytes </blue>\n")
|
|
||||||
}
|
|
||||||
|
|
||||||
printJobCreate(input, queue)
|
|
||||||
}
|
|
||||||
|
|
||||||
func printJobCreate(input DataStruct, queue *fifo.Queue) {
|
|
||||||
|
|
||||||
tml.Printf("<yellow>[" + config.Project + "]: Adding job #" + input.JobID + " to print queue</yellow>\n")
|
|
||||||
|
|
||||||
socket, err := net.Dial("tcp", config.PrinterAddr+":9100")
|
|
||||||
if err != nil {
|
|
||||||
println(err.Error())
|
|
||||||
}
|
|
||||||
defer func(socket net.Conn) {
|
|
||||||
err := socket.Close()
|
|
||||||
if err != nil {
|
|
||||||
println(err.Error())
|
|
||||||
}
|
|
||||||
}(socket)
|
|
||||||
|
|
||||||
p := escpos.New(socket)
|
|
||||||
p.SetConfig(escpos.ConfigEpsonTMT20II)
|
|
||||||
|
|
||||||
p.Initialize()
|
|
||||||
p.DefaultLineSpacing()
|
|
||||||
|
|
||||||
for _, item := range input.Data {
|
|
||||||
if item.Type <= 0 || item.Type > 7 {
|
|
||||||
tml.Printf("<red>[" + config.Project + "]: Job #" + input.JobID + " bad type</red>\n")
|
|
||||||
return
|
|
||||||
} else if item.Size <= 0 || item.Size > 16 {
|
|
||||||
tml.Printf("<red>[" + config.Project + "]: Job #" + input.JobID + " bad size</red>\n")
|
|
||||||
return
|
|
||||||
} else {
|
|
||||||
switch item.Type {
|
|
||||||
case 1:
|
|
||||||
// Generate Regular Text
|
|
||||||
p.Bold(false).Size(uint8(item.Size), uint8(item.Size)).Write(item.Text)
|
|
||||||
case 2:
|
|
||||||
// Generate Bold Text
|
|
||||||
p.Bold(true).Size(uint8(item.Size), uint8(item.Size)).Write(item.Text)
|
|
||||||
case 3:
|
|
||||||
// Generate QR Code
|
|
||||||
p.QRCode(item.Text, true, uint8(item.Size), escpos.QRCodeErrorCorrectionLevelH)
|
|
||||||
case 4:
|
|
||||||
// New Line
|
|
||||||
p.LineFeed()
|
|
||||||
case 5:
|
|
||||||
// New Line X amount of times
|
|
||||||
p.LineFeedD(uint8(item.Size))
|
|
||||||
case 6:
|
|
||||||
// Decode Base64Raw Input
|
|
||||||
/*
|
|
||||||
base64_decoded, err := base64.StdEncoding.DecodeString(item.Text)
|
|
||||||
if err != nil {
|
|
||||||
tml.Printf("<red>[" + config.Project + "]: Job #" + input.JobID + " base64 decode failed</red>\n")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
*/
|
|
||||||
hex_decoded, err := hex.DecodeString(item.Text)
|
|
||||||
if err != nil {
|
|
||||||
tml.Printf("<red>[" + config.Project + "]: Job #" + input.JobID + " hex decode failed</red>\n")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
p.WriteRaw([]byte(hex_decoded))
|
|
||||||
case 7:
|
|
||||||
// Print Image from URL
|
|
||||||
response, err := http.Get(item.Text)
|
|
||||||
if err != nil {
|
|
||||||
tml.Printf("<red>[" + config.Project + "]: Job #" + input.JobID + " image load failed</red>\n")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
defer response.Body.Close()
|
|
||||||
|
|
||||||
if response.StatusCode != 200 {
|
|
||||||
tml.Printf("<red>[" + config.Project + "]: Job #" + input.JobID + " image load failed - received non 200 response code</red>\n")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
img, _, err := image.Decode(response.Body)
|
|
||||||
if err != nil {
|
|
||||||
tml.Printf("<red>[" + config.Project + "]: Job #" + input.JobID + " image decode failed</red>\n")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
p.PrintImage(img)
|
|
||||||
|
|
||||||
response.Body.Close()
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
tml.Printf("<yellow>[" + config.Project + "]: Printing job #" + input.JobID + "</yellow>\n")
|
|
||||||
|
|
||||||
p.LineFeed()
|
|
||||||
err = p.PrintAndCut()
|
|
||||||
if err != nil {
|
|
||||||
println(err.Error())
|
|
||||||
}
|
|
||||||
|
|
||||||
tml.Printf("<green>[" + config.Project + "]: Done printing #" + input.JobID + "</green>\n")
|
|
||||||
|
|
||||||
socket.Close()
|
|
||||||
}
|
|
||||||
@@ -1,160 +0,0 @@
|
|||||||
package service
|
|
||||||
|
|
||||||
import (
|
|
||||||
fifo "github.com/foize/go.fifo"
|
|
||||||
sentryecho "github.com/getsentry/sentry-go/echo"
|
|
||||||
"github.com/golang-jwt/jwt/v5"
|
|
||||||
"github.com/labstack/echo-jwt/v4"
|
|
||||||
"github.com/labstack/echo/v4"
|
|
||||||
"github.com/labstack/echo/v4/middleware"
|
|
||||||
"golang.org/x/time/rate"
|
|
||||||
"log"
|
|
||||||
"net/http"
|
|
||||||
"strconv"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"uberbringer/config"
|
|
||||||
"uberbringer/snowflake"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Queue struct {
|
|
||||||
Data []Item `json:"data"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type InputData struct {
|
|
||||||
Data []Item `json:"data"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type DataStruct struct {
|
|
||||||
JobID string `json:"job"`
|
|
||||||
Data []Item `json:"data"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type Item struct {
|
|
||||||
Type int `json:"type"`
|
|
||||||
Size int `json:"size"`
|
|
||||||
Text string `json:"text"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type jwtCustomClaims struct {
|
|
||||||
jwt.RegisteredClaims
|
|
||||||
}
|
|
||||||
|
|
||||||
func StartEcho(server chan bool, webserver_addr string, webserver_port int) {
|
|
||||||
|
|
||||||
queue := fifo.NewQueue()
|
|
||||||
|
|
||||||
// Start Echo
|
|
||||||
e := echo.New()
|
|
||||||
|
|
||||||
e.Use(middleware.Logger())
|
|
||||||
e.Use(middleware.Recover())
|
|
||||||
e.Use(middleware.RateLimiter(middleware.NewRateLimiterMemoryStore(rate.Limit(1))))
|
|
||||||
|
|
||||||
// Echo GZIP
|
|
||||||
e.Use(middleware.GzipWithConfig(middleware.GzipConfig{
|
|
||||||
Level: 3,
|
|
||||||
}))
|
|
||||||
|
|
||||||
// Echo Request ID
|
|
||||||
e.Use(middleware.RequestIDWithConfig(middleware.RequestIDConfig{
|
|
||||||
Generator: func() string {
|
|
||||||
var idGeneratorSettings *snowflake.Settings
|
|
||||||
|
|
||||||
// build snowflake using the IdGenerator API
|
|
||||||
idGeneratorSettings = &snowflake.Settings{}
|
|
||||||
idGeneratorSettings.StartTime = time.Date(2016, 1, 1, 0, 0, 0, 0, time.UTC)
|
|
||||||
|
|
||||||
SnowFlakeID, err := snowflake.GenerateID(idGeneratorSettings)
|
|
||||||
if err != nil {
|
|
||||||
log.Println(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return strconv.FormatUint(SnowFlakeID.List[0], 10)
|
|
||||||
},
|
|
||||||
}))
|
|
||||||
|
|
||||||
// Once it's done, you can attach the handler as one of your middleware
|
|
||||||
e.Use(sentryecho.New(sentryecho.Options{
|
|
||||||
Repanic: true,
|
|
||||||
}))
|
|
||||||
|
|
||||||
// API Routes
|
|
||||||
|
|
||||||
// API Version 1
|
|
||||||
api_v1 := e.Group("/api/v1")
|
|
||||||
|
|
||||||
// Echo JWT - Won't accept valid keys? Bug To-Do
|
|
||||||
api_v1.Use(echojwt.WithConfig(echojwt.Config{
|
|
||||||
SigningKey: []byte(config.JWT_Secret),
|
|
||||||
SigningMethod: "HS256",
|
|
||||||
TokenLookup: "header:Authorization:Bearer ,query:token, param:token",
|
|
||||||
ContextKey: "User",
|
|
||||||
NewClaimsFunc: func(c echo.Context) jwt.Claims {
|
|
||||||
return new(jwtCustomClaims)
|
|
||||||
},
|
|
||||||
}))
|
|
||||||
|
|
||||||
api_v1.POST("/print", func(c echo.Context) error {
|
|
||||||
|
|
||||||
var idGeneratorSettings *snowflake.Settings
|
|
||||||
idGeneratorSettings = &snowflake.Settings{}
|
|
||||||
idGeneratorSettings.StartTime = time.Date(2025, 1, 1, 0, 0, 0, 0, time.UTC)
|
|
||||||
SnowFlakeID, err := snowflake.GenerateID(idGeneratorSettings)
|
|
||||||
if err != nil {
|
|
||||||
log.Println(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
var printJob string
|
|
||||||
printJob = strconv.FormatUint(SnowFlakeID.List[0], 10)
|
|
||||||
|
|
||||||
data := new(InputData)
|
|
||||||
if err := c.Bind(data); err != nil {
|
|
||||||
return c.String(http.StatusBadRequest, "bad request")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Load into separate struct for security
|
|
||||||
toPrint := DataStruct{
|
|
||||||
JobID: printJob,
|
|
||||||
}
|
|
||||||
|
|
||||||
toPrint.Data = data.Data
|
|
||||||
|
|
||||||
printJobCreate(toPrint, queue)
|
|
||||||
|
|
||||||
return c.String(http.StatusOK, "OK - "+printJob)
|
|
||||||
})
|
|
||||||
|
|
||||||
e.GET("/robots.txt", func(c echo.Context) error {
|
|
||||||
return c.String(http.StatusOK, "User-agent: *\nDisallow:\n")
|
|
||||||
})
|
|
||||||
|
|
||||||
e.GET("/", func(c echo.Context) error {
|
|
||||||
|
|
||||||
// Project Information
|
|
||||||
type ProjectInformation struct {
|
|
||||||
Project string `json:"Project" xml:"Project"`
|
|
||||||
Description string `json:"Description" xml:"Description"`
|
|
||||||
Authors string `json:"Authors" xml:"Authors"`
|
|
||||||
Version string `json:"Version" xml:"Version"`
|
|
||||||
Build string `json:"Build" xml:"Build"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// Build Response
|
|
||||||
Response := &ProjectInformation{
|
|
||||||
Project: string(config.Project),
|
|
||||||
Description: string(config.Description),
|
|
||||||
Authors: string(config.Authors),
|
|
||||||
Version: string(config.Version),
|
|
||||||
Build: string(config.Build),
|
|
||||||
}
|
|
||||||
|
|
||||||
// Return Response
|
|
||||||
return c.JSONPretty(http.StatusOK, Response, " ")
|
|
||||||
}).Name = "Base"
|
|
||||||
|
|
||||||
e.Logger.Fatal(e.Start(webserver_addr + ":" + strconv.Itoa(webserver_port)))
|
|
||||||
|
|
||||||
server <- true
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,311 +0,0 @@
|
|||||||
package snowflake
|
|
||||||
|
|
||||||
import (
|
|
||||||
"errors"
|
|
||||||
"io/ioutil"
|
|
||||||
"log"
|
|
||||||
"net"
|
|
||||||
"net/http"
|
|
||||||
"os"
|
|
||||||
"sync"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
// These constants are the bit lengths of SnowFlake ID parts.
|
|
||||||
const (
|
|
||||||
BitLenTime = 39 // bit length of time
|
|
||||||
BitLenMachineID = 63 - BitLenTime - BitLenSequence // bit length of machine id (16 bits)
|
|
||||||
BitLenSequence = 8 // bit length of sequence number
|
|
||||||
)
|
|
||||||
|
|
||||||
// Settings configures SnowFlake:
|
|
||||||
//
|
|
||||||
// StartTime is the time since which the SnowFlake time is defined as the elapsed time.
|
|
||||||
// If StartTime is 0, the start time of the SnowFlake is set to "2014-09-01 00:00:00 +0000 UTC".
|
|
||||||
// If StartTime is ahead of the current time, SnowFlake is not created.
|
|
||||||
//
|
|
||||||
// MachineID returns the unique ID of the SnowFlake instance.
|
|
||||||
// If MachineID returns an error, SnowFlake is not created.
|
|
||||||
// If MachineID is nil, default MachineID is used.
|
|
||||||
// Default MachineID returns the lower 16 bits of the private IP address.
|
|
||||||
//
|
|
||||||
// CheckMachineID validates the uniqueness of the machine ID.
|
|
||||||
// If CheckMachineID returns false, SnowFlake is not created.
|
|
||||||
// If CheckMachineID is nil, no validation is done.
|
|
||||||
type Settings struct {
|
|
||||||
StartTime time.Time
|
|
||||||
MachineID func() (uint16, error)
|
|
||||||
CheckMachineID func(uint16) bool
|
|
||||||
}
|
|
||||||
|
|
||||||
// SnowFlake is a distributed unique ID generator.
|
|
||||||
type SnowFlake struct {
|
|
||||||
mutex *sync.Mutex
|
|
||||||
startTime int64
|
|
||||||
recentTime int64 // most recent time when this snowflake was used
|
|
||||||
sequence uint16
|
|
||||||
machineID uint16
|
|
||||||
}
|
|
||||||
|
|
||||||
type IDList struct {
|
|
||||||
List []uint64 `json:"id_list"`
|
|
||||||
MachineId uint16 `json:"machine_id"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func initSnowFlake(st *Settings) *SnowFlake {
|
|
||||||
if st == nil {
|
|
||||||
st = &Settings{}
|
|
||||||
// Default start-time is the Jan 01, 2014 and the ID generator should work for 174 yeard from then
|
|
||||||
st.StartTime = time.Date(2014, 1, 1, 0, 0, 0, 0, time.UTC)
|
|
||||||
}
|
|
||||||
sf := NewSnowFlake(*st)
|
|
||||||
if sf == nil {
|
|
||||||
log.Println("snowFlake not created")
|
|
||||||
}
|
|
||||||
return sf
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
func GenerateID(settings *Settings) (*IDList, error) {
|
|
||||||
snowFlake := initSnowFlake(settings)
|
|
||||||
ids, err := snowFlake.NextIDs()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
idList := &IDList{List: ids, MachineId: snowFlake.machineID}
|
|
||||||
return idList, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewSnowFlake returns a new SnowFlake configured with the given Settings.
|
|
||||||
// NewSnowFlake returns nil in the following cases:
|
|
||||||
// - Settings.StartTime is ahead of the current time.
|
|
||||||
// - Settings.MachineID returns an error.
|
|
||||||
// - Settings.CheckMachineID returns false.
|
|
||||||
func NewSnowFlake(st Settings) *SnowFlake {
|
|
||||||
sf := new(SnowFlake)
|
|
||||||
sf.mutex = new(sync.Mutex)
|
|
||||||
// why is it set to max value ?
|
|
||||||
sf.sequence = uint16(1<<BitLenSequence - 1)
|
|
||||||
if st.StartTime.After(time.Now()) {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
if st.StartTime.IsZero() {
|
|
||||||
sf.startTime = toSnowFlakeTime(time.Date(2014, 9, 1, 0, 0, 0, 0, time.UTC))
|
|
||||||
} else {
|
|
||||||
sf.startTime = toSnowFlakeTime(st.StartTime)
|
|
||||||
}
|
|
||||||
|
|
||||||
var err error
|
|
||||||
if st.MachineID == nil {
|
|
||||||
sf.machineID, err = lower16BitPrivateIP()
|
|
||||||
} else {
|
|
||||||
sf.machineID, err = st.MachineID()
|
|
||||||
}
|
|
||||||
if err != nil || (st.CheckMachineID != nil && !st.CheckMachineID(sf.machineID)) {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
return sf
|
|
||||||
}
|
|
||||||
|
|
||||||
// elapsedTime, machine-id and sequence
|
|
||||||
func (sf *SnowFlake) NextIDs() ([]uint64, error) {
|
|
||||||
sf.mutex.Lock()
|
|
||||||
defer sf.mutex.Unlock()
|
|
||||||
//sf.elapsedTime = currentElapsedTime(sf.startTime)
|
|
||||||
sf.validateTime()
|
|
||||||
sf.sequence = 0
|
|
||||||
const maxSequence = uint16(1<<BitLenSequence - 1)
|
|
||||||
idList := make([]uint64, 0, maxSequence+1)
|
|
||||||
for sf.sequence <= maxSequence {
|
|
||||||
id, err := sf.toID()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
idList = append(idList, id)
|
|
||||||
sf.sequence = (sf.sequence + 1)
|
|
||||||
}
|
|
||||||
return idList, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// NextID generates a next unique ID.
|
|
||||||
// After the SnowFlake time overflows, NextID returns an error.
|
|
||||||
// ONLY USED in Testing ??
|
|
||||||
func (sf *SnowFlake) NextID() (uint64, error) {
|
|
||||||
sf.mutex.Lock()
|
|
||||||
defer sf.mutex.Unlock()
|
|
||||||
sf.validateTime()
|
|
||||||
return sf.toID()
|
|
||||||
}
|
|
||||||
|
|
||||||
// checks if the current time (time elapsed since the start of this snowflake instances start) is less than the most recent
|
|
||||||
// snowflake time. If the recentTime is less than the current time -- meaning the id has not been generated in a while --
|
|
||||||
// update the recent time to current time and set the sequence to 0. The sequence is set to zero since new ids will be generated in this time.
|
|
||||||
// if recentTime time is equal to or greater than current time -- find the number of ids that have already been generated by updating the sequence.
|
|
||||||
// if the ids is 0 -- meaning all ids at the current time has been generated -- sleep for the time until the next time slot is available
|
|
||||||
func (sf *SnowFlake) validateTime() {
|
|
||||||
current := currentElapsedTime(sf.startTime)
|
|
||||||
if sf.recentTime < current {
|
|
||||||
// this is only executed the first time
|
|
||||||
// this will be executed if the elapsedTime is not set correctly to current time
|
|
||||||
sf.recentTime = current
|
|
||||||
sf.sequence = 0
|
|
||||||
} else if sf.recentTime == current {
|
|
||||||
const maskSequence = uint16(1<<BitLenSequence - 1)
|
|
||||||
sf.sequence = (sf.sequence + 1) & maskSequence
|
|
||||||
if sf.sequence == 0 {
|
|
||||||
sf.recentTime++
|
|
||||||
overtime := sf.recentTime - current
|
|
||||||
time.Sleep(sleepTime((overtime)))
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
log.Fatal("recent time can never be greater than current time")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
func (sf *SnowFlake) NextIDRange() (uint64, uint64, error) {
|
|
||||||
sf.mutex.Lock()
|
|
||||||
defer sf.mutex.Unlock()
|
|
||||||
sf.validateTime()
|
|
||||||
lower, err := sf.toID()
|
|
||||||
if err != nil {
|
|
||||||
return 0, 0, err
|
|
||||||
}
|
|
||||||
sf.sequence = uint16(1<<BitLenSequence - 1)
|
|
||||||
upper, err := sf.toID()
|
|
||||||
if err != nil {
|
|
||||||
return 0, 0, err
|
|
||||||
}
|
|
||||||
return lower, upper, nil
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
const snowFlakeTimeUnitScaleFactor = 1e7 // nsec, i.e. 10 msec convert unit of nano-sec to 10 msec.
|
|
||||||
|
|
||||||
func toSnowFlakeTime(t time.Time) int64 {
|
|
||||||
return t.UTC().UnixNano() / snowFlakeTimeUnitScaleFactor
|
|
||||||
}
|
|
||||||
|
|
||||||
func currentElapsedTime(startTime int64) int64 {
|
|
||||||
return toSnowFlakeTime(time.Now()) - startTime
|
|
||||||
}
|
|
||||||
|
|
||||||
func sleepTime(overtime int64) time.Duration {
|
|
||||||
return time.Duration(overtime)*10*time.Millisecond -
|
|
||||||
time.Duration(time.Now().UTC().UnixNano()%snowFlakeTimeUnitScaleFactor)*time.Nanosecond
|
|
||||||
}
|
|
||||||
|
|
||||||
func (sf *SnowFlake) toID() (uint64, error) {
|
|
||||||
if sf.recentTime >= 1<<BitLenTime {
|
|
||||||
return 0, errors.New("over the time limit")
|
|
||||||
}
|
|
||||||
// Time-Sequence-MachineID
|
|
||||||
//return uint64(sf.elapsedTime)<<(BitLenSequence+BitLenMachineID) |
|
|
||||||
// uint64(sf.sequence)<<BitLenMachineID |
|
|
||||||
// uint64(sf.machineID), nil
|
|
||||||
|
|
||||||
// Time-MachineID-Sequence
|
|
||||||
return uint64(sf.recentTime)<<(BitLenSequence+BitLenMachineID) |
|
|
||||||
uint64(sf.machineID)<<BitLenSequence |
|
|
||||||
uint64(sf.sequence), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func privateIPv4() (net.IP, error) {
|
|
||||||
as, err := net.InterfaceAddrs()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, a := range as {
|
|
||||||
ipnet, ok := a.(*net.IPNet)
|
|
||||||
if !ok || ipnet.IP.IsLoopback() {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
ip := ipnet.IP.To4()
|
|
||||||
if isPrivateIPv4(ip) {
|
|
||||||
return ip, nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil, errors.New("no private ip address")
|
|
||||||
}
|
|
||||||
|
|
||||||
func amazonEC2PrivateIPv4() (net.IP, error) {
|
|
||||||
// URL to retrieve instance metadata in an AWS EC2 instance:
|
|
||||||
// http://docs.aws.amazon.com/en_us/AWSEC2/latest/UserGuide/ec2-instance-metadata.html
|
|
||||||
timeout := time.Duration(10 * time.Millisecond)
|
|
||||||
client := http.Client{
|
|
||||||
Timeout: timeout,
|
|
||||||
}
|
|
||||||
res, err := client.Get("http://169.254.169.254/latest/meta-data/local-ipv4")
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
defer res.Body.Close()
|
|
||||||
|
|
||||||
body, err := ioutil.ReadAll(res.Body)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
ip := net.ParseIP(string(body))
|
|
||||||
if ip == nil {
|
|
||||||
return nil, errors.New("invalid ip address")
|
|
||||||
}
|
|
||||||
return ip.To4(), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func k8sPodIPFromEnvVariable() (net.IP, error) {
|
|
||||||
podIpEnvVarKey := "UNIQUE_ID_POD_IP"
|
|
||||||
podIpStr := os.Getenv(podIpEnvVarKey)
|
|
||||||
if podIpStr == "" {
|
|
||||||
return nil, errors.New("Env Variable Not Present")
|
|
||||||
}
|
|
||||||
ip := net.ParseIP(podIpStr)
|
|
||||||
if ip == nil {
|
|
||||||
return nil, errors.New("invalid ip address")
|
|
||||||
}
|
|
||||||
return ip.To4(), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func isPrivateIPv4(ip net.IP) bool {
|
|
||||||
return ip != nil &&
|
|
||||||
(ip[0] == 10 || ip[0] == 172 && (ip[1] >= 16 && ip[1] < 32) || ip[0] == 192 && ip[1] == 168)
|
|
||||||
}
|
|
||||||
|
|
||||||
func lower16BitPrivateIP() (uint16, error) {
|
|
||||||
ip, err := k8sPodIPFromEnvVariable()
|
|
||||||
if err != nil {
|
|
||||||
ip, err = amazonEC2PrivateIPv4()
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
ip, err = privateIPv4()
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return uint16(ip[2])<<8 + uint16(ip[3]), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Decompose returns a set of SnowFlake ID parts.
|
|
||||||
// Time-MachineID-Sequence
|
|
||||||
func decompose(id uint64) map[string]uint64 {
|
|
||||||
// const maskSequence = uint64((1<<BitLenSequence - 1) << BitLenMachineID)
|
|
||||||
const maskSequence = uint64((1<<BitLenSequence - 1))
|
|
||||||
//const maskMachineID = uint64(1<<BitLenMachineID - 1)
|
|
||||||
const maskMachineID = uint64((1<<BitLenMachineID - 1) << BitLenSequence)
|
|
||||||
msb := id >> 63
|
|
||||||
time := id >> (BitLenSequence + BitLenMachineID)
|
|
||||||
//sequence := id & maskSequence >> BitLenMachineID
|
|
||||||
sequence := id & maskSequence
|
|
||||||
|
|
||||||
machineID := id & maskMachineID >> BitLenSequence
|
|
||||||
|
|
||||||
return map[string]uint64{
|
|
||||||
"id": id,
|
|
||||||
"msb": msb,
|
|
||||||
"time": time,
|
|
||||||
"sequence": sequence,
|
|
||||||
"machine-id": machineID,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,55 +0,0 @@
|
|||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"log"
|
|
||||||
"net/http"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/getsentry/sentry-go"
|
|
||||||
"github.com/liamg/tml"
|
|
||||||
"uberbringer/cmd"
|
|
||||||
"uberbringer/config"
|
|
||||||
)
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
|
|
||||||
//// ***** Start Sentry ***** ////
|
|
||||||
tml.Printf("<bold><cyan>[" + config.Project + "]: Initializing Error Reporting...</cyan></bold>\n")
|
|
||||||
|
|
||||||
sentrySyncTransport := sentry.NewHTTPSyncTransport()
|
|
||||||
sentrySyncTransport.Timeout = time.Second * 3
|
|
||||||
|
|
||||||
err := sentry.Init(sentry.ClientOptions{
|
|
||||||
// Either set your DSN here or set the SENTRY_DSN environment variable.
|
|
||||||
Dsn: config.SentryDSN,
|
|
||||||
// Either set environment and release here or set the SENTRY_ENVIRONMENT
|
|
||||||
// and SENTRY_RELEASE environment variables.
|
|
||||||
Environment: "Production",
|
|
||||||
Release: config.Project + "@" + config.Version,
|
|
||||||
// Enable printing of SDK debug messages.
|
|
||||||
Debug: true,
|
|
||||||
// Useful when getting started or trying to figure something out.
|
|
||||||
AttachStacktrace: true,
|
|
||||||
Transport: sentrySyncTransport,
|
|
||||||
BeforeSend: func(event *sentry.Event, hint *sentry.EventHint) *sentry.Event {
|
|
||||||
if hint.Context != nil {
|
|
||||||
if req, ok := hint.Context.Value(sentry.RequestContextKey).(*http.Request); ok {
|
|
||||||
// You have access to the original Request
|
|
||||||
log.Println(req)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
log.Println(event)
|
|
||||||
return event
|
|
||||||
},
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
log.Fatalf("["+config.Project+"]: Sentry initialization failed: %v\n", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Flush buffered events before the program terminates.
|
|
||||||
// Set the timeout to the maximum duration the program can afford to wait.
|
|
||||||
defer sentry.Flush(2 * time.Second)
|
|
||||||
//// ***** End Sentry ***** ////
|
|
||||||
|
|
||||||
cmd.Execute()
|
|
||||||
}
|
|
||||||
-2
@@ -1,2 +0,0 @@
|
|||||||
/toml.test
|
|
||||||
/toml-test
|
|
||||||
-21
@@ -1,21 +0,0 @@
|
|||||||
The MIT License (MIT)
|
|
||||||
|
|
||||||
Copyright (c) 2013 TOML authors
|
|
||||||
|
|
||||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
||||||
of this software and associated documentation files (the "Software"), to deal
|
|
||||||
in the Software without restriction, including without limitation the rights
|
|
||||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
||||||
copies of the Software, and to permit persons to whom the Software is
|
|
||||||
furnished to do so, subject to the following conditions:
|
|
||||||
|
|
||||||
The above copyright notice and this permission notice shall be included in
|
|
||||||
all copies or substantial portions of the Software.
|
|
||||||
|
|
||||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
||||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
||||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
||||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
||||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
||||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
|
||||||
THE SOFTWARE.
|
|
||||||
-120
@@ -1,120 +0,0 @@
|
|||||||
TOML stands for Tom's Obvious, Minimal Language. This Go package provides a
|
|
||||||
reflection interface similar to Go's standard library `json` and `xml` packages.
|
|
||||||
|
|
||||||
Compatible with TOML version [v1.0.0](https://toml.io/en/v1.0.0).
|
|
||||||
|
|
||||||
Documentation: https://godocs.io/github.com/BurntSushi/toml
|
|
||||||
|
|
||||||
See the [releases page](https://github.com/BurntSushi/toml/releases) for a
|
|
||||||
changelog; this information is also in the git tag annotations (e.g. `git show
|
|
||||||
v0.4.0`).
|
|
||||||
|
|
||||||
This library requires Go 1.18 or newer; add it to your go.mod with:
|
|
||||||
|
|
||||||
% go get github.com/BurntSushi/toml@latest
|
|
||||||
|
|
||||||
It also comes with a TOML validator CLI tool:
|
|
||||||
|
|
||||||
% go install github.com/BurntSushi/toml/cmd/tomlv@latest
|
|
||||||
% tomlv some-toml-file.toml
|
|
||||||
|
|
||||||
### Examples
|
|
||||||
For the simplest example, consider some TOML file as just a list of keys and
|
|
||||||
values:
|
|
||||||
|
|
||||||
```toml
|
|
||||||
Age = 25
|
|
||||||
Cats = [ "Cauchy", "Plato" ]
|
|
||||||
Pi = 3.14
|
|
||||||
Perfection = [ 6, 28, 496, 8128 ]
|
|
||||||
DOB = 1987-07-05T05:45:00Z
|
|
||||||
```
|
|
||||||
|
|
||||||
Which can be decoded with:
|
|
||||||
|
|
||||||
```go
|
|
||||||
type Config struct {
|
|
||||||
Age int
|
|
||||||
Cats []string
|
|
||||||
Pi float64
|
|
||||||
Perfection []int
|
|
||||||
DOB time.Time
|
|
||||||
}
|
|
||||||
|
|
||||||
var conf Config
|
|
||||||
_, err := toml.Decode(tomlData, &conf)
|
|
||||||
```
|
|
||||||
|
|
||||||
You can also use struct tags if your struct field name doesn't map to a TOML key
|
|
||||||
value directly:
|
|
||||||
|
|
||||||
```toml
|
|
||||||
some_key_NAME = "wat"
|
|
||||||
```
|
|
||||||
|
|
||||||
```go
|
|
||||||
type TOML struct {
|
|
||||||
ObscureKey string `toml:"some_key_NAME"`
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Beware that like other decoders **only exported fields** are considered when
|
|
||||||
encoding and decoding; private fields are silently ignored.
|
|
||||||
|
|
||||||
### Using the `Marshaler` and `encoding.TextUnmarshaler` interfaces
|
|
||||||
Here's an example that automatically parses values in a `mail.Address`:
|
|
||||||
|
|
||||||
```toml
|
|
||||||
contacts = [
|
|
||||||
"Donald Duck <donald@duckburg.com>",
|
|
||||||
"Scrooge McDuck <scrooge@duckburg.com>",
|
|
||||||
]
|
|
||||||
```
|
|
||||||
|
|
||||||
Can be decoded with:
|
|
||||||
|
|
||||||
```go
|
|
||||||
// Create address type which satisfies the encoding.TextUnmarshaler interface.
|
|
||||||
type address struct {
|
|
||||||
*mail.Address
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a *address) UnmarshalText(text []byte) error {
|
|
||||||
var err error
|
|
||||||
a.Address, err = mail.ParseAddress(string(text))
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
// Decode it.
|
|
||||||
func decode() {
|
|
||||||
blob := `
|
|
||||||
contacts = [
|
|
||||||
"Donald Duck <donald@duckburg.com>",
|
|
||||||
"Scrooge McDuck <scrooge@duckburg.com>",
|
|
||||||
]
|
|
||||||
`
|
|
||||||
|
|
||||||
var contacts struct {
|
|
||||||
Contacts []address
|
|
||||||
}
|
|
||||||
|
|
||||||
_, err := toml.Decode(blob, &contacts)
|
|
||||||
if err != nil {
|
|
||||||
log.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, c := range contacts.Contacts {
|
|
||||||
fmt.Printf("%#v\n", c.Address)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Output:
|
|
||||||
// &mail.Address{Name:"Donald Duck", Address:"donald@duckburg.com"}
|
|
||||||
// &mail.Address{Name:"Scrooge McDuck", Address:"scrooge@duckburg.com"}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
To target TOML specifically you can implement `UnmarshalTOML` TOML interface in
|
|
||||||
a similar way.
|
|
||||||
|
|
||||||
### More complex usage
|
|
||||||
See the [`_example/`](/_example) directory for a more complex example.
|
|
||||||
-613
@@ -1,613 +0,0 @@
|
|||||||
package toml
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"encoding"
|
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
"io/fs"
|
|
||||||
"math"
|
|
||||||
"os"
|
|
||||||
"reflect"
|
|
||||||
"strconv"
|
|
||||||
"strings"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Unmarshaler is the interface implemented by objects that can unmarshal a
|
|
||||||
// TOML description of themselves.
|
|
||||||
type Unmarshaler interface {
|
|
||||||
UnmarshalTOML(any) error
|
|
||||||
}
|
|
||||||
|
|
||||||
// Unmarshal decodes the contents of data in TOML format into a pointer v.
|
|
||||||
//
|
|
||||||
// See [Decoder] for a description of the decoding process.
|
|
||||||
func Unmarshal(data []byte, v any) error {
|
|
||||||
_, err := NewDecoder(bytes.NewReader(data)).Decode(v)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
// Decode the TOML data in to the pointer v.
|
|
||||||
//
|
|
||||||
// See [Decoder] for a description of the decoding process.
|
|
||||||
func Decode(data string, v any) (MetaData, error) {
|
|
||||||
return NewDecoder(strings.NewReader(data)).Decode(v)
|
|
||||||
}
|
|
||||||
|
|
||||||
// DecodeFile reads the contents of a file and decodes it with [Decode].
|
|
||||||
func DecodeFile(path string, v any) (MetaData, error) {
|
|
||||||
fp, err := os.Open(path)
|
|
||||||
if err != nil {
|
|
||||||
return MetaData{}, err
|
|
||||||
}
|
|
||||||
defer fp.Close()
|
|
||||||
return NewDecoder(fp).Decode(v)
|
|
||||||
}
|
|
||||||
|
|
||||||
// DecodeFS reads the contents of a file from [fs.FS] and decodes it with
|
|
||||||
// [Decode].
|
|
||||||
func DecodeFS(fsys fs.FS, path string, v any) (MetaData, error) {
|
|
||||||
fp, err := fsys.Open(path)
|
|
||||||
if err != nil {
|
|
||||||
return MetaData{}, err
|
|
||||||
}
|
|
||||||
defer fp.Close()
|
|
||||||
return NewDecoder(fp).Decode(v)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Primitive is a TOML value that hasn't been decoded into a Go value.
|
|
||||||
//
|
|
||||||
// This type can be used for any value, which will cause decoding to be delayed.
|
|
||||||
// You can use [PrimitiveDecode] to "manually" decode these values.
|
|
||||||
//
|
|
||||||
// NOTE: The underlying representation of a `Primitive` value is subject to
|
|
||||||
// change. Do not rely on it.
|
|
||||||
//
|
|
||||||
// NOTE: Primitive values are still parsed, so using them will only avoid the
|
|
||||||
// overhead of reflection. They can be useful when you don't know the exact type
|
|
||||||
// of TOML data until runtime.
|
|
||||||
type Primitive struct {
|
|
||||||
undecoded any
|
|
||||||
context Key
|
|
||||||
}
|
|
||||||
|
|
||||||
// The significand precision for float32 and float64 is 24 and 53 bits; this is
|
|
||||||
// the range a natural number can be stored in a float without loss of data.
|
|
||||||
const (
|
|
||||||
maxSafeFloat32Int = 16777215 // 2^24-1
|
|
||||||
maxSafeFloat64Int = int64(9007199254740991) // 2^53-1
|
|
||||||
)
|
|
||||||
|
|
||||||
// Decoder decodes TOML data.
|
|
||||||
//
|
|
||||||
// TOML tables correspond to Go structs or maps; they can be used
|
|
||||||
// interchangeably, but structs offer better type safety.
|
|
||||||
//
|
|
||||||
// TOML table arrays correspond to either a slice of structs or a slice of maps.
|
|
||||||
//
|
|
||||||
// TOML datetimes correspond to [time.Time]. Local datetimes are parsed in the
|
|
||||||
// local timezone.
|
|
||||||
//
|
|
||||||
// [time.Duration] types are treated as nanoseconds if the TOML value is an
|
|
||||||
// integer, or they're parsed with time.ParseDuration() if they're strings.
|
|
||||||
//
|
|
||||||
// All other TOML types (float, string, int, bool and array) correspond to the
|
|
||||||
// obvious Go types.
|
|
||||||
//
|
|
||||||
// An exception to the above rules is if a type implements the TextUnmarshaler
|
|
||||||
// interface, in which case any primitive TOML value (floats, strings, integers,
|
|
||||||
// booleans, datetimes) will be converted to a []byte and given to the value's
|
|
||||||
// UnmarshalText method. See the Unmarshaler example for a demonstration with
|
|
||||||
// email addresses.
|
|
||||||
//
|
|
||||||
// # Key mapping
|
|
||||||
//
|
|
||||||
// TOML keys can map to either keys in a Go map or field names in a Go struct.
|
|
||||||
// The special `toml` struct tag can be used to map TOML keys to struct fields
|
|
||||||
// that don't match the key name exactly (see the example). A case insensitive
|
|
||||||
// match to struct names will be tried if an exact match can't be found.
|
|
||||||
//
|
|
||||||
// The mapping between TOML values and Go values is loose. That is, there may
|
|
||||||
// exist TOML values that cannot be placed into your representation, and there
|
|
||||||
// may be parts of your representation that do not correspond to TOML values.
|
|
||||||
// This loose mapping can be made stricter by using the IsDefined and/or
|
|
||||||
// Undecoded methods on the MetaData returned.
|
|
||||||
//
|
|
||||||
// This decoder does not handle cyclic types. Decode will not terminate if a
|
|
||||||
// cyclic type is passed.
|
|
||||||
type Decoder struct {
|
|
||||||
r io.Reader
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewDecoder creates a new Decoder.
|
|
||||||
func NewDecoder(r io.Reader) *Decoder {
|
|
||||||
return &Decoder{r: r}
|
|
||||||
}
|
|
||||||
|
|
||||||
var (
|
|
||||||
unmarshalToml = reflect.TypeOf((*Unmarshaler)(nil)).Elem()
|
|
||||||
unmarshalText = reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem()
|
|
||||||
primitiveType = reflect.TypeOf((*Primitive)(nil)).Elem()
|
|
||||||
)
|
|
||||||
|
|
||||||
// Decode TOML data in to the pointer `v`.
|
|
||||||
func (dec *Decoder) Decode(v any) (MetaData, error) {
|
|
||||||
rv := reflect.ValueOf(v)
|
|
||||||
if rv.Kind() != reflect.Ptr {
|
|
||||||
s := "%q"
|
|
||||||
if reflect.TypeOf(v) == nil {
|
|
||||||
s = "%v"
|
|
||||||
}
|
|
||||||
|
|
||||||
return MetaData{}, fmt.Errorf("toml: cannot decode to non-pointer "+s, reflect.TypeOf(v))
|
|
||||||
}
|
|
||||||
if rv.IsNil() {
|
|
||||||
return MetaData{}, fmt.Errorf("toml: cannot decode to nil value of %q", reflect.TypeOf(v))
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check if this is a supported type: struct, map, any, or something that
|
|
||||||
// implements UnmarshalTOML or UnmarshalText.
|
|
||||||
rv = indirect(rv)
|
|
||||||
rt := rv.Type()
|
|
||||||
if rv.Kind() != reflect.Struct && rv.Kind() != reflect.Map &&
|
|
||||||
!(rv.Kind() == reflect.Interface && rv.NumMethod() == 0) &&
|
|
||||||
!rt.Implements(unmarshalToml) && !rt.Implements(unmarshalText) {
|
|
||||||
return MetaData{}, fmt.Errorf("toml: cannot decode to type %s", rt)
|
|
||||||
}
|
|
||||||
|
|
||||||
// TODO: parser should read from io.Reader? Or at the very least, make it
|
|
||||||
// read from []byte rather than string
|
|
||||||
data, err := io.ReadAll(dec.r)
|
|
||||||
if err != nil {
|
|
||||||
return MetaData{}, err
|
|
||||||
}
|
|
||||||
|
|
||||||
p, err := parse(string(data))
|
|
||||||
if err != nil {
|
|
||||||
return MetaData{}, err
|
|
||||||
}
|
|
||||||
|
|
||||||
md := MetaData{
|
|
||||||
mapping: p.mapping,
|
|
||||||
keyInfo: p.keyInfo,
|
|
||||||
keys: p.ordered,
|
|
||||||
decoded: make(map[string]struct{}, len(p.ordered)),
|
|
||||||
context: nil,
|
|
||||||
data: data,
|
|
||||||
}
|
|
||||||
return md, md.unify(p.mapping, rv)
|
|
||||||
}
|
|
||||||
|
|
||||||
// PrimitiveDecode is just like the other Decode* functions, except it decodes a
|
|
||||||
// TOML value that has already been parsed. Valid primitive values can *only* be
|
|
||||||
// obtained from values filled by the decoder functions, including this method.
|
|
||||||
// (i.e., v may contain more [Primitive] values.)
|
|
||||||
//
|
|
||||||
// Meta data for primitive values is included in the meta data returned by the
|
|
||||||
// Decode* functions with one exception: keys returned by the Undecoded method
|
|
||||||
// will only reflect keys that were decoded. Namely, any keys hidden behind a
|
|
||||||
// Primitive will be considered undecoded. Executing this method will update the
|
|
||||||
// undecoded keys in the meta data. (See the example.)
|
|
||||||
func (md *MetaData) PrimitiveDecode(primValue Primitive, v any) error {
|
|
||||||
md.context = primValue.context
|
|
||||||
defer func() { md.context = nil }()
|
|
||||||
return md.unify(primValue.undecoded, rvalue(v))
|
|
||||||
}
|
|
||||||
|
|
||||||
// unify performs a sort of type unification based on the structure of `rv`,
|
|
||||||
// which is the client representation.
|
|
||||||
//
|
|
||||||
// Any type mismatch produces an error. Finding a type that we don't know
|
|
||||||
// how to handle produces an unsupported type error.
|
|
||||||
func (md *MetaData) unify(data any, rv reflect.Value) error {
|
|
||||||
// Special case. Look for a `Primitive` value.
|
|
||||||
// TODO: #76 would make this superfluous after implemented.
|
|
||||||
if rv.Type() == primitiveType {
|
|
||||||
// Save the undecoded data and the key context into the primitive
|
|
||||||
// value.
|
|
||||||
context := make(Key, len(md.context))
|
|
||||||
copy(context, md.context)
|
|
||||||
rv.Set(reflect.ValueOf(Primitive{
|
|
||||||
undecoded: data,
|
|
||||||
context: context,
|
|
||||||
}))
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
rvi := rv.Interface()
|
|
||||||
if v, ok := rvi.(Unmarshaler); ok {
|
|
||||||
err := v.UnmarshalTOML(data)
|
|
||||||
if err != nil {
|
|
||||||
return md.parseErr(err)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
if v, ok := rvi.(encoding.TextUnmarshaler); ok {
|
|
||||||
return md.unifyText(data, v)
|
|
||||||
}
|
|
||||||
|
|
||||||
// TODO:
|
|
||||||
// The behavior here is incorrect whenever a Go type satisfies the
|
|
||||||
// encoding.TextUnmarshaler interface but also corresponds to a TOML hash or
|
|
||||||
// array. In particular, the unmarshaler should only be applied to primitive
|
|
||||||
// TOML values. But at this point, it will be applied to all kinds of values
|
|
||||||
// and produce an incorrect error whenever those values are hashes or arrays
|
|
||||||
// (including arrays of tables).
|
|
||||||
|
|
||||||
k := rv.Kind()
|
|
||||||
|
|
||||||
if k >= reflect.Int && k <= reflect.Uint64 {
|
|
||||||
return md.unifyInt(data, rv)
|
|
||||||
}
|
|
||||||
switch k {
|
|
||||||
case reflect.Struct:
|
|
||||||
return md.unifyStruct(data, rv)
|
|
||||||
case reflect.Map:
|
|
||||||
return md.unifyMap(data, rv)
|
|
||||||
case reflect.Array:
|
|
||||||
return md.unifyArray(data, rv)
|
|
||||||
case reflect.Slice:
|
|
||||||
return md.unifySlice(data, rv)
|
|
||||||
case reflect.String:
|
|
||||||
return md.unifyString(data, rv)
|
|
||||||
case reflect.Bool:
|
|
||||||
return md.unifyBool(data, rv)
|
|
||||||
case reflect.Interface:
|
|
||||||
if rv.NumMethod() > 0 { /// Only empty interfaces are supported.
|
|
||||||
return md.e("unsupported type %s", rv.Type())
|
|
||||||
}
|
|
||||||
return md.unifyAnything(data, rv)
|
|
||||||
case reflect.Float32, reflect.Float64:
|
|
||||||
return md.unifyFloat64(data, rv)
|
|
||||||
}
|
|
||||||
return md.e("unsupported type %s", rv.Kind())
|
|
||||||
}
|
|
||||||
|
|
||||||
func (md *MetaData) unifyStruct(mapping any, rv reflect.Value) error {
|
|
||||||
tmap, ok := mapping.(map[string]any)
|
|
||||||
if !ok {
|
|
||||||
if mapping == nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return md.e("type mismatch for %s: expected table but found %s", rv.Type().String(), fmtType(mapping))
|
|
||||||
}
|
|
||||||
|
|
||||||
for key, datum := range tmap {
|
|
||||||
var f *field
|
|
||||||
fields := cachedTypeFields(rv.Type())
|
|
||||||
for i := range fields {
|
|
||||||
ff := &fields[i]
|
|
||||||
if ff.name == key {
|
|
||||||
f = ff
|
|
||||||
break
|
|
||||||
}
|
|
||||||
if f == nil && strings.EqualFold(ff.name, key) {
|
|
||||||
f = ff
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if f != nil {
|
|
||||||
subv := rv
|
|
||||||
for _, i := range f.index {
|
|
||||||
subv = indirect(subv.Field(i))
|
|
||||||
}
|
|
||||||
|
|
||||||
if isUnifiable(subv) {
|
|
||||||
md.decoded[md.context.add(key).String()] = struct{}{}
|
|
||||||
md.context = append(md.context, key)
|
|
||||||
|
|
||||||
err := md.unify(datum, subv)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
md.context = md.context[0 : len(md.context)-1]
|
|
||||||
} else if f.name != "" {
|
|
||||||
return md.e("cannot write unexported field %s.%s", rv.Type().String(), f.name)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (md *MetaData) unifyMap(mapping any, rv reflect.Value) error {
|
|
||||||
keyType := rv.Type().Key().Kind()
|
|
||||||
if keyType != reflect.String && keyType != reflect.Interface {
|
|
||||||
return fmt.Errorf("toml: cannot decode to a map with non-string key type (%s in %q)",
|
|
||||||
keyType, rv.Type())
|
|
||||||
}
|
|
||||||
|
|
||||||
tmap, ok := mapping.(map[string]any)
|
|
||||||
if !ok {
|
|
||||||
if tmap == nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return md.badtype("map", mapping)
|
|
||||||
}
|
|
||||||
if rv.IsNil() {
|
|
||||||
rv.Set(reflect.MakeMap(rv.Type()))
|
|
||||||
}
|
|
||||||
for k, v := range tmap {
|
|
||||||
md.decoded[md.context.add(k).String()] = struct{}{}
|
|
||||||
md.context = append(md.context, k)
|
|
||||||
|
|
||||||
rvval := reflect.Indirect(reflect.New(rv.Type().Elem()))
|
|
||||||
|
|
||||||
err := md.unify(v, indirect(rvval))
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
md.context = md.context[0 : len(md.context)-1]
|
|
||||||
|
|
||||||
rvkey := indirect(reflect.New(rv.Type().Key()))
|
|
||||||
|
|
||||||
switch keyType {
|
|
||||||
case reflect.Interface:
|
|
||||||
rvkey.Set(reflect.ValueOf(k))
|
|
||||||
case reflect.String:
|
|
||||||
rvkey.SetString(k)
|
|
||||||
}
|
|
||||||
|
|
||||||
rv.SetMapIndex(rvkey, rvval)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (md *MetaData) unifyArray(data any, rv reflect.Value) error {
|
|
||||||
datav := reflect.ValueOf(data)
|
|
||||||
if datav.Kind() != reflect.Slice {
|
|
||||||
if !datav.IsValid() {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return md.badtype("slice", data)
|
|
||||||
}
|
|
||||||
if l := datav.Len(); l != rv.Len() {
|
|
||||||
return md.e("expected array length %d; got TOML array of length %d", rv.Len(), l)
|
|
||||||
}
|
|
||||||
return md.unifySliceArray(datav, rv)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (md *MetaData) unifySlice(data any, rv reflect.Value) error {
|
|
||||||
datav := reflect.ValueOf(data)
|
|
||||||
if datav.Kind() != reflect.Slice {
|
|
||||||
if !datav.IsValid() {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return md.badtype("slice", data)
|
|
||||||
}
|
|
||||||
n := datav.Len()
|
|
||||||
if rv.IsNil() || rv.Cap() < n {
|
|
||||||
rv.Set(reflect.MakeSlice(rv.Type(), n, n))
|
|
||||||
}
|
|
||||||
rv.SetLen(n)
|
|
||||||
return md.unifySliceArray(datav, rv)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (md *MetaData) unifySliceArray(data, rv reflect.Value) error {
|
|
||||||
l := data.Len()
|
|
||||||
for i := 0; i < l; i++ {
|
|
||||||
err := md.unify(data.Index(i).Interface(), indirect(rv.Index(i)))
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (md *MetaData) unifyString(data any, rv reflect.Value) error {
|
|
||||||
_, ok := rv.Interface().(json.Number)
|
|
||||||
if ok {
|
|
||||||
if i, ok := data.(int64); ok {
|
|
||||||
rv.SetString(strconv.FormatInt(i, 10))
|
|
||||||
} else if f, ok := data.(float64); ok {
|
|
||||||
rv.SetString(strconv.FormatFloat(f, 'f', -1, 64))
|
|
||||||
} else {
|
|
||||||
return md.badtype("string", data)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
if s, ok := data.(string); ok {
|
|
||||||
rv.SetString(s)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return md.badtype("string", data)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (md *MetaData) unifyFloat64(data any, rv reflect.Value) error {
|
|
||||||
rvk := rv.Kind()
|
|
||||||
|
|
||||||
if num, ok := data.(float64); ok {
|
|
||||||
switch rvk {
|
|
||||||
case reflect.Float32:
|
|
||||||
if num < -math.MaxFloat32 || num > math.MaxFloat32 {
|
|
||||||
return md.parseErr(errParseRange{i: num, size: rvk.String()})
|
|
||||||
}
|
|
||||||
fallthrough
|
|
||||||
case reflect.Float64:
|
|
||||||
rv.SetFloat(num)
|
|
||||||
default:
|
|
||||||
panic("bug")
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
if num, ok := data.(int64); ok {
|
|
||||||
if (rvk == reflect.Float32 && (num < -maxSafeFloat32Int || num > maxSafeFloat32Int)) ||
|
|
||||||
(rvk == reflect.Float64 && (num < -maxSafeFloat64Int || num > maxSafeFloat64Int)) {
|
|
||||||
return md.parseErr(errUnsafeFloat{i: num, size: rvk.String()})
|
|
||||||
}
|
|
||||||
rv.SetFloat(float64(num))
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
return md.badtype("float", data)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (md *MetaData) unifyInt(data any, rv reflect.Value) error {
|
|
||||||
_, ok := rv.Interface().(time.Duration)
|
|
||||||
if ok {
|
|
||||||
// Parse as string duration, and fall back to regular integer parsing
|
|
||||||
// (as nanosecond) if this is not a string.
|
|
||||||
if s, ok := data.(string); ok {
|
|
||||||
dur, err := time.ParseDuration(s)
|
|
||||||
if err != nil {
|
|
||||||
return md.parseErr(errParseDuration{s})
|
|
||||||
}
|
|
||||||
rv.SetInt(int64(dur))
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
num, ok := data.(int64)
|
|
||||||
if !ok {
|
|
||||||
return md.badtype("integer", data)
|
|
||||||
}
|
|
||||||
|
|
||||||
rvk := rv.Kind()
|
|
||||||
switch {
|
|
||||||
case rvk >= reflect.Int && rvk <= reflect.Int64:
|
|
||||||
if (rvk == reflect.Int8 && (num < math.MinInt8 || num > math.MaxInt8)) ||
|
|
||||||
(rvk == reflect.Int16 && (num < math.MinInt16 || num > math.MaxInt16)) ||
|
|
||||||
(rvk == reflect.Int32 && (num < math.MinInt32 || num > math.MaxInt32)) {
|
|
||||||
return md.parseErr(errParseRange{i: num, size: rvk.String()})
|
|
||||||
}
|
|
||||||
rv.SetInt(num)
|
|
||||||
case rvk >= reflect.Uint && rvk <= reflect.Uint64:
|
|
||||||
unum := uint64(num)
|
|
||||||
if rvk == reflect.Uint8 && (num < 0 || unum > math.MaxUint8) ||
|
|
||||||
rvk == reflect.Uint16 && (num < 0 || unum > math.MaxUint16) ||
|
|
||||||
rvk == reflect.Uint32 && (num < 0 || unum > math.MaxUint32) {
|
|
||||||
return md.parseErr(errParseRange{i: num, size: rvk.String()})
|
|
||||||
}
|
|
||||||
rv.SetUint(unum)
|
|
||||||
default:
|
|
||||||
panic("unreachable")
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (md *MetaData) unifyBool(data any, rv reflect.Value) error {
|
|
||||||
if b, ok := data.(bool); ok {
|
|
||||||
rv.SetBool(b)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return md.badtype("boolean", data)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (md *MetaData) unifyAnything(data any, rv reflect.Value) error {
|
|
||||||
rv.Set(reflect.ValueOf(data))
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (md *MetaData) unifyText(data any, v encoding.TextUnmarshaler) error {
|
|
||||||
var s string
|
|
||||||
switch sdata := data.(type) {
|
|
||||||
case Marshaler:
|
|
||||||
text, err := sdata.MarshalTOML()
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
s = string(text)
|
|
||||||
case encoding.TextMarshaler:
|
|
||||||
text, err := sdata.MarshalText()
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
s = string(text)
|
|
||||||
case fmt.Stringer:
|
|
||||||
s = sdata.String()
|
|
||||||
case string:
|
|
||||||
s = sdata
|
|
||||||
case bool:
|
|
||||||
s = fmt.Sprintf("%v", sdata)
|
|
||||||
case int64:
|
|
||||||
s = fmt.Sprintf("%d", sdata)
|
|
||||||
case float64:
|
|
||||||
s = fmt.Sprintf("%f", sdata)
|
|
||||||
default:
|
|
||||||
return md.badtype("primitive (string-like)", data)
|
|
||||||
}
|
|
||||||
if err := v.UnmarshalText([]byte(s)); err != nil {
|
|
||||||
return md.parseErr(err)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (md *MetaData) badtype(dst string, data any) error {
|
|
||||||
return md.e("incompatible types: TOML value has type %s; destination has type %s", fmtType(data), dst)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (md *MetaData) parseErr(err error) error {
|
|
||||||
k := md.context.String()
|
|
||||||
return ParseError{
|
|
||||||
LastKey: k,
|
|
||||||
Position: md.keyInfo[k].pos,
|
|
||||||
Line: md.keyInfo[k].pos.Line,
|
|
||||||
err: err,
|
|
||||||
input: string(md.data),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (md *MetaData) e(format string, args ...any) error {
|
|
||||||
f := "toml: "
|
|
||||||
if len(md.context) > 0 {
|
|
||||||
f = fmt.Sprintf("toml: (last key %q): ", md.context)
|
|
||||||
p := md.keyInfo[md.context.String()].pos
|
|
||||||
if p.Line > 0 {
|
|
||||||
f = fmt.Sprintf("toml: line %d (last key %q): ", p.Line, md.context)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return fmt.Errorf(f+format, args...)
|
|
||||||
}
|
|
||||||
|
|
||||||
// rvalue returns a reflect.Value of `v`. All pointers are resolved.
|
|
||||||
func rvalue(v any) reflect.Value {
|
|
||||||
return indirect(reflect.ValueOf(v))
|
|
||||||
}
|
|
||||||
|
|
||||||
// indirect returns the value pointed to by a pointer.
|
|
||||||
//
|
|
||||||
// Pointers are followed until the value is not a pointer. New values are
|
|
||||||
// allocated for each nil pointer.
|
|
||||||
//
|
|
||||||
// An exception to this rule is if the value satisfies an interface of interest
|
|
||||||
// to us (like encoding.TextUnmarshaler).
|
|
||||||
func indirect(v reflect.Value) reflect.Value {
|
|
||||||
if v.Kind() != reflect.Ptr {
|
|
||||||
if v.CanSet() {
|
|
||||||
pv := v.Addr()
|
|
||||||
pvi := pv.Interface()
|
|
||||||
if _, ok := pvi.(encoding.TextUnmarshaler); ok {
|
|
||||||
return pv
|
|
||||||
}
|
|
||||||
if _, ok := pvi.(Unmarshaler); ok {
|
|
||||||
return pv
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return v
|
|
||||||
}
|
|
||||||
if v.IsNil() {
|
|
||||||
v.Set(reflect.New(v.Type().Elem()))
|
|
||||||
}
|
|
||||||
return indirect(reflect.Indirect(v))
|
|
||||||
}
|
|
||||||
|
|
||||||
func isUnifiable(rv reflect.Value) bool {
|
|
||||||
if rv.CanSet() {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
rvi := rv.Interface()
|
|
||||||
if _, ok := rvi.(encoding.TextUnmarshaler); ok {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
if _, ok := rvi.(Unmarshaler); ok {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
// fmt %T with "interface {}" replaced with "any", which is far more readable.
|
|
||||||
func fmtType(t any) string {
|
|
||||||
return strings.ReplaceAll(fmt.Sprintf("%T", t), "interface {}", "any")
|
|
||||||
}
|
|
||||||
-29
@@ -1,29 +0,0 @@
|
|||||||
package toml
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding"
|
|
||||||
"io"
|
|
||||||
)
|
|
||||||
|
|
||||||
// TextMarshaler is an alias for encoding.TextMarshaler.
|
|
||||||
//
|
|
||||||
// Deprecated: use encoding.TextMarshaler
|
|
||||||
type TextMarshaler encoding.TextMarshaler
|
|
||||||
|
|
||||||
// TextUnmarshaler is an alias for encoding.TextUnmarshaler.
|
|
||||||
//
|
|
||||||
// Deprecated: use encoding.TextUnmarshaler
|
|
||||||
type TextUnmarshaler encoding.TextUnmarshaler
|
|
||||||
|
|
||||||
// DecodeReader is an alias for NewDecoder(r).Decode(v).
|
|
||||||
//
|
|
||||||
// Deprecated: use NewDecoder(reader).Decode(&value).
|
|
||||||
func DecodeReader(r io.Reader, v any) (MetaData, error) { return NewDecoder(r).Decode(v) }
|
|
||||||
|
|
||||||
// PrimitiveDecode is an alias for MetaData.PrimitiveDecode().
|
|
||||||
//
|
|
||||||
// Deprecated: use MetaData.PrimitiveDecode.
|
|
||||||
func PrimitiveDecode(primValue Primitive, v any) error {
|
|
||||||
md := MetaData{decoded: make(map[string]struct{})}
|
|
||||||
return md.unify(primValue.undecoded, rvalue(v))
|
|
||||||
}
|
|
||||||
-8
@@ -1,8 +0,0 @@
|
|||||||
// Package toml implements decoding and encoding of TOML files.
|
|
||||||
//
|
|
||||||
// This package supports TOML v1.0.0, as specified at https://toml.io
|
|
||||||
//
|
|
||||||
// The github.com/BurntSushi/toml/cmd/tomlv package implements a TOML validator,
|
|
||||||
// and can be used to verify if TOML document is valid. It can also be used to
|
|
||||||
// print the type of each key.
|
|
||||||
package toml
|
|
||||||
-778
@@ -1,778 +0,0 @@
|
|||||||
package toml
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bufio"
|
|
||||||
"bytes"
|
|
||||||
"encoding"
|
|
||||||
"encoding/json"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
"math"
|
|
||||||
"reflect"
|
|
||||||
"sort"
|
|
||||||
"strconv"
|
|
||||||
"strings"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/BurntSushi/toml/internal"
|
|
||||||
)
|
|
||||||
|
|
||||||
type tomlEncodeError struct{ error }
|
|
||||||
|
|
||||||
var (
|
|
||||||
errArrayNilElement = errors.New("toml: cannot encode array with nil element")
|
|
||||||
errNonString = errors.New("toml: cannot encode a map with non-string key type")
|
|
||||||
errNoKey = errors.New("toml: top-level values must be Go maps or structs")
|
|
||||||
errAnything = errors.New("") // used in testing
|
|
||||||
)
|
|
||||||
|
|
||||||
var dblQuotedReplacer = strings.NewReplacer(
|
|
||||||
"\"", "\\\"",
|
|
||||||
"\\", "\\\\",
|
|
||||||
"\x00", `\u0000`,
|
|
||||||
"\x01", `\u0001`,
|
|
||||||
"\x02", `\u0002`,
|
|
||||||
"\x03", `\u0003`,
|
|
||||||
"\x04", `\u0004`,
|
|
||||||
"\x05", `\u0005`,
|
|
||||||
"\x06", `\u0006`,
|
|
||||||
"\x07", `\u0007`,
|
|
||||||
"\b", `\b`,
|
|
||||||
"\t", `\t`,
|
|
||||||
"\n", `\n`,
|
|
||||||
"\x0b", `\u000b`,
|
|
||||||
"\f", `\f`,
|
|
||||||
"\r", `\r`,
|
|
||||||
"\x0e", `\u000e`,
|
|
||||||
"\x0f", `\u000f`,
|
|
||||||
"\x10", `\u0010`,
|
|
||||||
"\x11", `\u0011`,
|
|
||||||
"\x12", `\u0012`,
|
|
||||||
"\x13", `\u0013`,
|
|
||||||
"\x14", `\u0014`,
|
|
||||||
"\x15", `\u0015`,
|
|
||||||
"\x16", `\u0016`,
|
|
||||||
"\x17", `\u0017`,
|
|
||||||
"\x18", `\u0018`,
|
|
||||||
"\x19", `\u0019`,
|
|
||||||
"\x1a", `\u001a`,
|
|
||||||
"\x1b", `\u001b`,
|
|
||||||
"\x1c", `\u001c`,
|
|
||||||
"\x1d", `\u001d`,
|
|
||||||
"\x1e", `\u001e`,
|
|
||||||
"\x1f", `\u001f`,
|
|
||||||
"\x7f", `\u007f`,
|
|
||||||
)
|
|
||||||
|
|
||||||
var (
|
|
||||||
marshalToml = reflect.TypeOf((*Marshaler)(nil)).Elem()
|
|
||||||
marshalText = reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem()
|
|
||||||
timeType = reflect.TypeOf((*time.Time)(nil)).Elem()
|
|
||||||
)
|
|
||||||
|
|
||||||
// Marshaler is the interface implemented by types that can marshal themselves
|
|
||||||
// into valid TOML.
|
|
||||||
type Marshaler interface {
|
|
||||||
MarshalTOML() ([]byte, error)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Marshal returns a TOML representation of the Go value.
|
|
||||||
//
|
|
||||||
// See [Encoder] for a description of the encoding process.
|
|
||||||
func Marshal(v any) ([]byte, error) {
|
|
||||||
buff := new(bytes.Buffer)
|
|
||||||
if err := NewEncoder(buff).Encode(v); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return buff.Bytes(), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Encoder encodes a Go to a TOML document.
|
|
||||||
//
|
|
||||||
// The mapping between Go values and TOML values should be precisely the same as
|
|
||||||
// for [Decode].
|
|
||||||
//
|
|
||||||
// time.Time is encoded as a RFC 3339 string, and time.Duration as its string
|
|
||||||
// representation.
|
|
||||||
//
|
|
||||||
// The [Marshaler] and [encoding.TextMarshaler] interfaces are supported to
|
|
||||||
// encoding the value as custom TOML.
|
|
||||||
//
|
|
||||||
// If you want to write arbitrary binary data then you will need to use
|
|
||||||
// something like base64 since TOML does not have any binary types.
|
|
||||||
//
|
|
||||||
// When encoding TOML hashes (Go maps or structs), keys without any sub-hashes
|
|
||||||
// are encoded first.
|
|
||||||
//
|
|
||||||
// Go maps will be sorted alphabetically by key for deterministic output.
|
|
||||||
//
|
|
||||||
// The toml struct tag can be used to provide the key name; if omitted the
|
|
||||||
// struct field name will be used. If the "omitempty" option is present the
|
|
||||||
// following value will be skipped:
|
|
||||||
//
|
|
||||||
// - arrays, slices, maps, and string with len of 0
|
|
||||||
// - struct with all zero values
|
|
||||||
// - bool false
|
|
||||||
//
|
|
||||||
// If omitzero is given all int and float types with a value of 0 will be
|
|
||||||
// skipped.
|
|
||||||
//
|
|
||||||
// Encoding Go values without a corresponding TOML representation will return an
|
|
||||||
// error. Examples of this includes maps with non-string keys, slices with nil
|
|
||||||
// elements, embedded non-struct types, and nested slices containing maps or
|
|
||||||
// structs. (e.g. [][]map[string]string is not allowed but []map[string]string
|
|
||||||
// is okay, as is []map[string][]string).
|
|
||||||
//
|
|
||||||
// NOTE: only exported keys are encoded due to the use of reflection. Unexported
|
|
||||||
// keys are silently discarded.
|
|
||||||
type Encoder struct {
|
|
||||||
Indent string // string for a single indentation level; default is two spaces.
|
|
||||||
hasWritten bool // written any output to w yet?
|
|
||||||
w *bufio.Writer
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewEncoder create a new Encoder.
|
|
||||||
func NewEncoder(w io.Writer) *Encoder {
|
|
||||||
return &Encoder{w: bufio.NewWriter(w), Indent: " "}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Encode writes a TOML representation of the Go value to the [Encoder]'s writer.
|
|
||||||
//
|
|
||||||
// An error is returned if the value given cannot be encoded to a valid TOML
|
|
||||||
// document.
|
|
||||||
func (enc *Encoder) Encode(v any) error {
|
|
||||||
rv := eindirect(reflect.ValueOf(v))
|
|
||||||
err := enc.safeEncode(Key([]string{}), rv)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return enc.w.Flush()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (enc *Encoder) safeEncode(key Key, rv reflect.Value) (err error) {
|
|
||||||
defer func() {
|
|
||||||
if r := recover(); r != nil {
|
|
||||||
if terr, ok := r.(tomlEncodeError); ok {
|
|
||||||
err = terr.error
|
|
||||||
return
|
|
||||||
}
|
|
||||||
panic(r)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
enc.encode(key, rv)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (enc *Encoder) encode(key Key, rv reflect.Value) {
|
|
||||||
// If we can marshal the type to text, then we use that. This prevents the
|
|
||||||
// encoder for handling these types as generic structs (or whatever the
|
|
||||||
// underlying type of a TextMarshaler is).
|
|
||||||
switch {
|
|
||||||
case isMarshaler(rv):
|
|
||||||
enc.writeKeyValue(key, rv, false)
|
|
||||||
return
|
|
||||||
case rv.Type() == primitiveType: // TODO: #76 would make this superfluous after implemented.
|
|
||||||
enc.encode(key, reflect.ValueOf(rv.Interface().(Primitive).undecoded))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
k := rv.Kind()
|
|
||||||
switch k {
|
|
||||||
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32,
|
|
||||||
reflect.Int64,
|
|
||||||
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32,
|
|
||||||
reflect.Uint64,
|
|
||||||
reflect.Float32, reflect.Float64, reflect.String, reflect.Bool:
|
|
||||||
enc.writeKeyValue(key, rv, false)
|
|
||||||
case reflect.Array, reflect.Slice:
|
|
||||||
if typeEqual(tomlArrayHash, tomlTypeOfGo(rv)) {
|
|
||||||
enc.eArrayOfTables(key, rv)
|
|
||||||
} else {
|
|
||||||
enc.writeKeyValue(key, rv, false)
|
|
||||||
}
|
|
||||||
case reflect.Interface:
|
|
||||||
if rv.IsNil() {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
enc.encode(key, rv.Elem())
|
|
||||||
case reflect.Map:
|
|
||||||
if rv.IsNil() {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
enc.eTable(key, rv)
|
|
||||||
case reflect.Ptr:
|
|
||||||
if rv.IsNil() {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
enc.encode(key, rv.Elem())
|
|
||||||
case reflect.Struct:
|
|
||||||
enc.eTable(key, rv)
|
|
||||||
default:
|
|
||||||
encPanic(fmt.Errorf("unsupported type for key '%s': %s", key, k))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// eElement encodes any value that can be an array element.
|
|
||||||
func (enc *Encoder) eElement(rv reflect.Value) {
|
|
||||||
switch v := rv.Interface().(type) {
|
|
||||||
case time.Time: // Using TextMarshaler adds extra quotes, which we don't want.
|
|
||||||
format := time.RFC3339Nano
|
|
||||||
switch v.Location() {
|
|
||||||
case internal.LocalDatetime:
|
|
||||||
format = "2006-01-02T15:04:05.999999999"
|
|
||||||
case internal.LocalDate:
|
|
||||||
format = "2006-01-02"
|
|
||||||
case internal.LocalTime:
|
|
||||||
format = "15:04:05.999999999"
|
|
||||||
}
|
|
||||||
switch v.Location() {
|
|
||||||
default:
|
|
||||||
enc.wf(v.Format(format))
|
|
||||||
case internal.LocalDatetime, internal.LocalDate, internal.LocalTime:
|
|
||||||
enc.wf(v.In(time.UTC).Format(format))
|
|
||||||
}
|
|
||||||
return
|
|
||||||
case Marshaler:
|
|
||||||
s, err := v.MarshalTOML()
|
|
||||||
if err != nil {
|
|
||||||
encPanic(err)
|
|
||||||
}
|
|
||||||
if s == nil {
|
|
||||||
encPanic(errors.New("MarshalTOML returned nil and no error"))
|
|
||||||
}
|
|
||||||
enc.w.Write(s)
|
|
||||||
return
|
|
||||||
case encoding.TextMarshaler:
|
|
||||||
s, err := v.MarshalText()
|
|
||||||
if err != nil {
|
|
||||||
encPanic(err)
|
|
||||||
}
|
|
||||||
if s == nil {
|
|
||||||
encPanic(errors.New("MarshalText returned nil and no error"))
|
|
||||||
}
|
|
||||||
enc.writeQuoted(string(s))
|
|
||||||
return
|
|
||||||
case time.Duration:
|
|
||||||
enc.writeQuoted(v.String())
|
|
||||||
return
|
|
||||||
case json.Number:
|
|
||||||
n, _ := rv.Interface().(json.Number)
|
|
||||||
|
|
||||||
if n == "" { /// Useful zero value.
|
|
||||||
enc.w.WriteByte('0')
|
|
||||||
return
|
|
||||||
} else if v, err := n.Int64(); err == nil {
|
|
||||||
enc.eElement(reflect.ValueOf(v))
|
|
||||||
return
|
|
||||||
} else if v, err := n.Float64(); err == nil {
|
|
||||||
enc.eElement(reflect.ValueOf(v))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
encPanic(fmt.Errorf("unable to convert %q to int64 or float64", n))
|
|
||||||
}
|
|
||||||
|
|
||||||
switch rv.Kind() {
|
|
||||||
case reflect.Ptr:
|
|
||||||
enc.eElement(rv.Elem())
|
|
||||||
return
|
|
||||||
case reflect.String:
|
|
||||||
enc.writeQuoted(rv.String())
|
|
||||||
case reflect.Bool:
|
|
||||||
enc.wf(strconv.FormatBool(rv.Bool()))
|
|
||||||
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
|
|
||||||
enc.wf(strconv.FormatInt(rv.Int(), 10))
|
|
||||||
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
|
|
||||||
enc.wf(strconv.FormatUint(rv.Uint(), 10))
|
|
||||||
case reflect.Float32:
|
|
||||||
f := rv.Float()
|
|
||||||
if math.IsNaN(f) {
|
|
||||||
if math.Signbit(f) {
|
|
||||||
enc.wf("-")
|
|
||||||
}
|
|
||||||
enc.wf("nan")
|
|
||||||
} else if math.IsInf(f, 0) {
|
|
||||||
if math.Signbit(f) {
|
|
||||||
enc.wf("-")
|
|
||||||
}
|
|
||||||
enc.wf("inf")
|
|
||||||
} else {
|
|
||||||
enc.wf(floatAddDecimal(strconv.FormatFloat(f, 'f', -1, 32)))
|
|
||||||
}
|
|
||||||
case reflect.Float64:
|
|
||||||
f := rv.Float()
|
|
||||||
if math.IsNaN(f) {
|
|
||||||
if math.Signbit(f) {
|
|
||||||
enc.wf("-")
|
|
||||||
}
|
|
||||||
enc.wf("nan")
|
|
||||||
} else if math.IsInf(f, 0) {
|
|
||||||
if math.Signbit(f) {
|
|
||||||
enc.wf("-")
|
|
||||||
}
|
|
||||||
enc.wf("inf")
|
|
||||||
} else {
|
|
||||||
enc.wf(floatAddDecimal(strconv.FormatFloat(f, 'f', -1, 64)))
|
|
||||||
}
|
|
||||||
case reflect.Array, reflect.Slice:
|
|
||||||
enc.eArrayOrSliceElement(rv)
|
|
||||||
case reflect.Struct:
|
|
||||||
enc.eStruct(nil, rv, true)
|
|
||||||
case reflect.Map:
|
|
||||||
enc.eMap(nil, rv, true)
|
|
||||||
case reflect.Interface:
|
|
||||||
enc.eElement(rv.Elem())
|
|
||||||
default:
|
|
||||||
encPanic(fmt.Errorf("unexpected type: %s", fmtType(rv.Interface())))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// By the TOML spec, all floats must have a decimal with at least one number on
|
|
||||||
// either side.
|
|
||||||
func floatAddDecimal(fstr string) string {
|
|
||||||
if !strings.Contains(fstr, ".") {
|
|
||||||
return fstr + ".0"
|
|
||||||
}
|
|
||||||
return fstr
|
|
||||||
}
|
|
||||||
|
|
||||||
func (enc *Encoder) writeQuoted(s string) {
|
|
||||||
enc.wf("\"%s\"", dblQuotedReplacer.Replace(s))
|
|
||||||
}
|
|
||||||
|
|
||||||
func (enc *Encoder) eArrayOrSliceElement(rv reflect.Value) {
|
|
||||||
length := rv.Len()
|
|
||||||
enc.wf("[")
|
|
||||||
for i := 0; i < length; i++ {
|
|
||||||
elem := eindirect(rv.Index(i))
|
|
||||||
enc.eElement(elem)
|
|
||||||
if i != length-1 {
|
|
||||||
enc.wf(", ")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
enc.wf("]")
|
|
||||||
}
|
|
||||||
|
|
||||||
func (enc *Encoder) eArrayOfTables(key Key, rv reflect.Value) {
|
|
||||||
if len(key) == 0 {
|
|
||||||
encPanic(errNoKey)
|
|
||||||
}
|
|
||||||
for i := 0; i < rv.Len(); i++ {
|
|
||||||
trv := eindirect(rv.Index(i))
|
|
||||||
if isNil(trv) {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
enc.newline()
|
|
||||||
enc.wf("%s[[%s]]", enc.indentStr(key), key)
|
|
||||||
enc.newline()
|
|
||||||
enc.eMapOrStruct(key, trv, false)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (enc *Encoder) eTable(key Key, rv reflect.Value) {
|
|
||||||
if len(key) == 1 {
|
|
||||||
// Output an extra newline between top-level tables.
|
|
||||||
// (The newline isn't written if nothing else has been written though.)
|
|
||||||
enc.newline()
|
|
||||||
}
|
|
||||||
if len(key) > 0 {
|
|
||||||
enc.wf("%s[%s]", enc.indentStr(key), key)
|
|
||||||
enc.newline()
|
|
||||||
}
|
|
||||||
enc.eMapOrStruct(key, rv, false)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (enc *Encoder) eMapOrStruct(key Key, rv reflect.Value, inline bool) {
|
|
||||||
switch rv.Kind() {
|
|
||||||
case reflect.Map:
|
|
||||||
enc.eMap(key, rv, inline)
|
|
||||||
case reflect.Struct:
|
|
||||||
enc.eStruct(key, rv, inline)
|
|
||||||
default:
|
|
||||||
// Should never happen?
|
|
||||||
panic("eTable: unhandled reflect.Value Kind: " + rv.Kind().String())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (enc *Encoder) eMap(key Key, rv reflect.Value, inline bool) {
|
|
||||||
rt := rv.Type()
|
|
||||||
if rt.Key().Kind() != reflect.String {
|
|
||||||
encPanic(errNonString)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Sort keys so that we have deterministic output. And write keys directly
|
|
||||||
// underneath this key first, before writing sub-structs or sub-maps.
|
|
||||||
var mapKeysDirect, mapKeysSub []string
|
|
||||||
for _, mapKey := range rv.MapKeys() {
|
|
||||||
k := mapKey.String()
|
|
||||||
if typeIsTable(tomlTypeOfGo(eindirect(rv.MapIndex(mapKey)))) {
|
|
||||||
mapKeysSub = append(mapKeysSub, k)
|
|
||||||
} else {
|
|
||||||
mapKeysDirect = append(mapKeysDirect, k)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
var writeMapKeys = func(mapKeys []string, trailC bool) {
|
|
||||||
sort.Strings(mapKeys)
|
|
||||||
for i, mapKey := range mapKeys {
|
|
||||||
val := eindirect(rv.MapIndex(reflect.ValueOf(mapKey)))
|
|
||||||
if isNil(val) {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
if inline {
|
|
||||||
enc.writeKeyValue(Key{mapKey}, val, true)
|
|
||||||
if trailC || i != len(mapKeys)-1 {
|
|
||||||
enc.wf(", ")
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
enc.encode(key.add(mapKey), val)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if inline {
|
|
||||||
enc.wf("{")
|
|
||||||
}
|
|
||||||
writeMapKeys(mapKeysDirect, len(mapKeysSub) > 0)
|
|
||||||
writeMapKeys(mapKeysSub, false)
|
|
||||||
if inline {
|
|
||||||
enc.wf("}")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const is32Bit = (32 << (^uint(0) >> 63)) == 32
|
|
||||||
|
|
||||||
func pointerTo(t reflect.Type) reflect.Type {
|
|
||||||
if t.Kind() == reflect.Ptr {
|
|
||||||
return pointerTo(t.Elem())
|
|
||||||
}
|
|
||||||
return t
|
|
||||||
}
|
|
||||||
|
|
||||||
func (enc *Encoder) eStruct(key Key, rv reflect.Value, inline bool) {
|
|
||||||
// Write keys for fields directly under this key first, because if we write
|
|
||||||
// a field that creates a new table then all keys under it will be in that
|
|
||||||
// table (not the one we're writing here).
|
|
||||||
//
|
|
||||||
// Fields is a [][]int: for fieldsDirect this always has one entry (the
|
|
||||||
// struct index). For fieldsSub it contains two entries: the parent field
|
|
||||||
// index from tv, and the field indexes for the fields of the sub.
|
|
||||||
var (
|
|
||||||
rt = rv.Type()
|
|
||||||
fieldsDirect, fieldsSub [][]int
|
|
||||||
addFields func(rt reflect.Type, rv reflect.Value, start []int)
|
|
||||||
)
|
|
||||||
addFields = func(rt reflect.Type, rv reflect.Value, start []int) {
|
|
||||||
for i := 0; i < rt.NumField(); i++ {
|
|
||||||
f := rt.Field(i)
|
|
||||||
isEmbed := f.Anonymous && pointerTo(f.Type).Kind() == reflect.Struct
|
|
||||||
if f.PkgPath != "" && !isEmbed { /// Skip unexported fields.
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
opts := getOptions(f.Tag)
|
|
||||||
if opts.skip {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
frv := eindirect(rv.Field(i))
|
|
||||||
|
|
||||||
if is32Bit {
|
|
||||||
// Copy so it works correct on 32bit archs; not clear why this
|
|
||||||
// is needed. See #314, and https://www.reddit.com/r/golang/comments/pnx8v4
|
|
||||||
// This also works fine on 64bit, but 32bit archs are somewhat
|
|
||||||
// rare and this is a wee bit faster.
|
|
||||||
copyStart := make([]int, len(start))
|
|
||||||
copy(copyStart, start)
|
|
||||||
start = copyStart
|
|
||||||
}
|
|
||||||
|
|
||||||
// Treat anonymous struct fields with tag names as though they are
|
|
||||||
// not anonymous, like encoding/json does.
|
|
||||||
//
|
|
||||||
// Non-struct anonymous fields use the normal encoding logic.
|
|
||||||
if isEmbed {
|
|
||||||
if getOptions(f.Tag).name == "" && frv.Kind() == reflect.Struct {
|
|
||||||
addFields(frv.Type(), frv, append(start, f.Index...))
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if typeIsTable(tomlTypeOfGo(frv)) {
|
|
||||||
fieldsSub = append(fieldsSub, append(start, f.Index...))
|
|
||||||
} else {
|
|
||||||
fieldsDirect = append(fieldsDirect, append(start, f.Index...))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
addFields(rt, rv, nil)
|
|
||||||
|
|
||||||
writeFields := func(fields [][]int) {
|
|
||||||
for _, fieldIndex := range fields {
|
|
||||||
fieldType := rt.FieldByIndex(fieldIndex)
|
|
||||||
fieldVal := rv.FieldByIndex(fieldIndex)
|
|
||||||
|
|
||||||
opts := getOptions(fieldType.Tag)
|
|
||||||
if opts.skip {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if opts.omitempty && isEmpty(fieldVal) {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
fieldVal = eindirect(fieldVal)
|
|
||||||
|
|
||||||
if isNil(fieldVal) { /// Don't write anything for nil fields.
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
keyName := fieldType.Name
|
|
||||||
if opts.name != "" {
|
|
||||||
keyName = opts.name
|
|
||||||
}
|
|
||||||
|
|
||||||
if opts.omitzero && isZero(fieldVal) {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
if inline {
|
|
||||||
enc.writeKeyValue(Key{keyName}, fieldVal, true)
|
|
||||||
if fieldIndex[0] != len(fields)-1 {
|
|
||||||
enc.wf(", ")
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
enc.encode(key.add(keyName), fieldVal)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if inline {
|
|
||||||
enc.wf("{")
|
|
||||||
}
|
|
||||||
writeFields(fieldsDirect)
|
|
||||||
writeFields(fieldsSub)
|
|
||||||
if inline {
|
|
||||||
enc.wf("}")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// tomlTypeOfGo returns the TOML type name of the Go value's type.
|
|
||||||
//
|
|
||||||
// It is used to determine whether the types of array elements are mixed (which
|
|
||||||
// is forbidden). If the Go value is nil, then it is illegal for it to be an
|
|
||||||
// array element, and valueIsNil is returned as true.
|
|
||||||
//
|
|
||||||
// The type may be `nil`, which means no concrete TOML type could be found.
|
|
||||||
func tomlTypeOfGo(rv reflect.Value) tomlType {
|
|
||||||
if isNil(rv) || !rv.IsValid() {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
if rv.Kind() == reflect.Struct {
|
|
||||||
if rv.Type() == timeType {
|
|
||||||
return tomlDatetime
|
|
||||||
}
|
|
||||||
if isMarshaler(rv) {
|
|
||||||
return tomlString
|
|
||||||
}
|
|
||||||
return tomlHash
|
|
||||||
}
|
|
||||||
|
|
||||||
if isMarshaler(rv) {
|
|
||||||
return tomlString
|
|
||||||
}
|
|
||||||
|
|
||||||
switch rv.Kind() {
|
|
||||||
case reflect.Bool:
|
|
||||||
return tomlBool
|
|
||||||
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32,
|
|
||||||
reflect.Int64,
|
|
||||||
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32,
|
|
||||||
reflect.Uint64:
|
|
||||||
return tomlInteger
|
|
||||||
case reflect.Float32, reflect.Float64:
|
|
||||||
return tomlFloat
|
|
||||||
case reflect.Array, reflect.Slice:
|
|
||||||
if isTableArray(rv) {
|
|
||||||
return tomlArrayHash
|
|
||||||
}
|
|
||||||
return tomlArray
|
|
||||||
case reflect.Ptr, reflect.Interface:
|
|
||||||
return tomlTypeOfGo(rv.Elem())
|
|
||||||
case reflect.String:
|
|
||||||
return tomlString
|
|
||||||
case reflect.Map:
|
|
||||||
return tomlHash
|
|
||||||
default:
|
|
||||||
encPanic(errors.New("unsupported type: " + rv.Kind().String()))
|
|
||||||
panic("unreachable")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func isMarshaler(rv reflect.Value) bool {
|
|
||||||
return rv.Type().Implements(marshalText) || rv.Type().Implements(marshalToml)
|
|
||||||
}
|
|
||||||
|
|
||||||
// isTableArray reports if all entries in the array or slice are a table.
|
|
||||||
func isTableArray(arr reflect.Value) bool {
|
|
||||||
if isNil(arr) || !arr.IsValid() || arr.Len() == 0 {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
ret := true
|
|
||||||
for i := 0; i < arr.Len(); i++ {
|
|
||||||
tt := tomlTypeOfGo(eindirect(arr.Index(i)))
|
|
||||||
// Don't allow nil.
|
|
||||||
if tt == nil {
|
|
||||||
encPanic(errArrayNilElement)
|
|
||||||
}
|
|
||||||
|
|
||||||
if ret && !typeEqual(tomlHash, tt) {
|
|
||||||
ret = false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return ret
|
|
||||||
}
|
|
||||||
|
|
||||||
type tagOptions struct {
|
|
||||||
skip bool // "-"
|
|
||||||
name string
|
|
||||||
omitempty bool
|
|
||||||
omitzero bool
|
|
||||||
}
|
|
||||||
|
|
||||||
func getOptions(tag reflect.StructTag) tagOptions {
|
|
||||||
t := tag.Get("toml")
|
|
||||||
if t == "-" {
|
|
||||||
return tagOptions{skip: true}
|
|
||||||
}
|
|
||||||
var opts tagOptions
|
|
||||||
parts := strings.Split(t, ",")
|
|
||||||
opts.name = parts[0]
|
|
||||||
for _, s := range parts[1:] {
|
|
||||||
switch s {
|
|
||||||
case "omitempty":
|
|
||||||
opts.omitempty = true
|
|
||||||
case "omitzero":
|
|
||||||
opts.omitzero = true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return opts
|
|
||||||
}
|
|
||||||
|
|
||||||
func isZero(rv reflect.Value) bool {
|
|
||||||
switch rv.Kind() {
|
|
||||||
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
|
|
||||||
return rv.Int() == 0
|
|
||||||
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
|
|
||||||
return rv.Uint() == 0
|
|
||||||
case reflect.Float32, reflect.Float64:
|
|
||||||
return rv.Float() == 0.0
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
func isEmpty(rv reflect.Value) bool {
|
|
||||||
switch rv.Kind() {
|
|
||||||
case reflect.Array, reflect.Slice, reflect.Map, reflect.String:
|
|
||||||
return rv.Len() == 0
|
|
||||||
case reflect.Struct:
|
|
||||||
if rv.Type().Comparable() {
|
|
||||||
return reflect.Zero(rv.Type()).Interface() == rv.Interface()
|
|
||||||
}
|
|
||||||
// Need to also check if all the fields are empty, otherwise something
|
|
||||||
// like this with uncomparable types will always return true:
|
|
||||||
//
|
|
||||||
// type a struct{ field b }
|
|
||||||
// type b struct{ s []string }
|
|
||||||
// s := a{field: b{s: []string{"AAA"}}}
|
|
||||||
for i := 0; i < rv.NumField(); i++ {
|
|
||||||
if !isEmpty(rv.Field(i)) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return true
|
|
||||||
case reflect.Bool:
|
|
||||||
return !rv.Bool()
|
|
||||||
case reflect.Ptr:
|
|
||||||
return rv.IsNil()
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
func (enc *Encoder) newline() {
|
|
||||||
if enc.hasWritten {
|
|
||||||
enc.wf("\n")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Write a key/value pair:
|
|
||||||
//
|
|
||||||
// key = <any value>
|
|
||||||
//
|
|
||||||
// This is also used for "k = v" in inline tables; so something like this will
|
|
||||||
// be written in three calls:
|
|
||||||
//
|
|
||||||
// ┌───────────────────┐
|
|
||||||
// │ ┌───┐ ┌────┐│
|
|
||||||
// v v v v vv
|
|
||||||
// key = {k = 1, k2 = 2}
|
|
||||||
func (enc *Encoder) writeKeyValue(key Key, val reflect.Value, inline bool) {
|
|
||||||
/// Marshaler used on top-level document; call eElement() to just call
|
|
||||||
/// Marshal{TOML,Text}.
|
|
||||||
if len(key) == 0 {
|
|
||||||
enc.eElement(val)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
enc.wf("%s%s = ", enc.indentStr(key), key.maybeQuoted(len(key)-1))
|
|
||||||
enc.eElement(val)
|
|
||||||
if !inline {
|
|
||||||
enc.newline()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (enc *Encoder) wf(format string, v ...any) {
|
|
||||||
_, err := fmt.Fprintf(enc.w, format, v...)
|
|
||||||
if err != nil {
|
|
||||||
encPanic(err)
|
|
||||||
}
|
|
||||||
enc.hasWritten = true
|
|
||||||
}
|
|
||||||
|
|
||||||
func (enc *Encoder) indentStr(key Key) string {
|
|
||||||
return strings.Repeat(enc.Indent, len(key)-1)
|
|
||||||
}
|
|
||||||
|
|
||||||
func encPanic(err error) {
|
|
||||||
panic(tomlEncodeError{err})
|
|
||||||
}
|
|
||||||
|
|
||||||
// Resolve any level of pointers to the actual value (e.g. **string → string).
|
|
||||||
func eindirect(v reflect.Value) reflect.Value {
|
|
||||||
if v.Kind() != reflect.Ptr && v.Kind() != reflect.Interface {
|
|
||||||
if isMarshaler(v) {
|
|
||||||
return v
|
|
||||||
}
|
|
||||||
if v.CanAddr() { /// Special case for marshalers; see #358.
|
|
||||||
if pv := v.Addr(); isMarshaler(pv) {
|
|
||||||
return pv
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return v
|
|
||||||
}
|
|
||||||
|
|
||||||
if v.IsNil() {
|
|
||||||
return v
|
|
||||||
}
|
|
||||||
|
|
||||||
return eindirect(v.Elem())
|
|
||||||
}
|
|
||||||
|
|
||||||
func isNil(rv reflect.Value) bool {
|
|
||||||
switch rv.Kind() {
|
|
||||||
case reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
|
|
||||||
return rv.IsNil()
|
|
||||||
default:
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-356
@@ -1,356 +0,0 @@
|
|||||||
package toml
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"strings"
|
|
||||||
)
|
|
||||||
|
|
||||||
// ParseError is returned when there is an error parsing the TOML syntax such as
|
|
||||||
// invalid syntax, duplicate keys, etc.
|
|
||||||
//
|
|
||||||
// In addition to the error message itself, you can also print detailed location
|
|
||||||
// information with context by using [ErrorWithPosition]:
|
|
||||||
//
|
|
||||||
// toml: error: Key 'fruit' was already created and cannot be used as an array.
|
|
||||||
//
|
|
||||||
// At line 4, column 2-7:
|
|
||||||
//
|
|
||||||
// 2 | fruit = []
|
|
||||||
// 3 |
|
|
||||||
// 4 | [[fruit]] # Not allowed
|
|
||||||
// ^^^^^
|
|
||||||
//
|
|
||||||
// [ErrorWithUsage] can be used to print the above with some more detailed usage
|
|
||||||
// guidance:
|
|
||||||
//
|
|
||||||
// toml: error: newlines not allowed within inline tables
|
|
||||||
//
|
|
||||||
// At line 1, column 18:
|
|
||||||
//
|
|
||||||
// 1 | x = [{ key = 42 #
|
|
||||||
// ^
|
|
||||||
//
|
|
||||||
// Error help:
|
|
||||||
//
|
|
||||||
// Inline tables must always be on a single line:
|
|
||||||
//
|
|
||||||
// table = {key = 42, second = 43}
|
|
||||||
//
|
|
||||||
// It is invalid to split them over multiple lines like so:
|
|
||||||
//
|
|
||||||
// # INVALID
|
|
||||||
// table = {
|
|
||||||
// key = 42,
|
|
||||||
// second = 43
|
|
||||||
// }
|
|
||||||
//
|
|
||||||
// Use regular for this:
|
|
||||||
//
|
|
||||||
// [table]
|
|
||||||
// key = 42
|
|
||||||
// second = 43
|
|
||||||
type ParseError struct {
|
|
||||||
Message string // Short technical message.
|
|
||||||
Usage string // Longer message with usage guidance; may be blank.
|
|
||||||
Position Position // Position of the error
|
|
||||||
LastKey string // Last parsed key, may be blank.
|
|
||||||
|
|
||||||
// Line the error occurred.
|
|
||||||
//
|
|
||||||
// Deprecated: use [Position].
|
|
||||||
Line int
|
|
||||||
|
|
||||||
err error
|
|
||||||
input string
|
|
||||||
}
|
|
||||||
|
|
||||||
// Position of an error.
|
|
||||||
type Position struct {
|
|
||||||
Line int // Line number, starting at 1.
|
|
||||||
Start int // Start of error, as byte offset starting at 0.
|
|
||||||
Len int // Lenght in bytes.
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pe ParseError) Error() string {
|
|
||||||
msg := pe.Message
|
|
||||||
if msg == "" { // Error from errorf()
|
|
||||||
msg = pe.err.Error()
|
|
||||||
}
|
|
||||||
|
|
||||||
if pe.LastKey == "" {
|
|
||||||
return fmt.Sprintf("toml: line %d: %s", pe.Position.Line, msg)
|
|
||||||
}
|
|
||||||
return fmt.Sprintf("toml: line %d (last key %q): %s",
|
|
||||||
pe.Position.Line, pe.LastKey, msg)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ErrorWithPosition returns the error with detailed location context.
|
|
||||||
//
|
|
||||||
// See the documentation on [ParseError].
|
|
||||||
func (pe ParseError) ErrorWithPosition() string {
|
|
||||||
if pe.input == "" { // Should never happen, but just in case.
|
|
||||||
return pe.Error()
|
|
||||||
}
|
|
||||||
|
|
||||||
var (
|
|
||||||
lines = strings.Split(pe.input, "\n")
|
|
||||||
col = pe.column(lines)
|
|
||||||
b = new(strings.Builder)
|
|
||||||
)
|
|
||||||
|
|
||||||
msg := pe.Message
|
|
||||||
if msg == "" {
|
|
||||||
msg = pe.err.Error()
|
|
||||||
}
|
|
||||||
|
|
||||||
// TODO: don't show control characters as literals? This may not show up
|
|
||||||
// well everywhere.
|
|
||||||
|
|
||||||
if pe.Position.Len == 1 {
|
|
||||||
fmt.Fprintf(b, "toml: error: %s\n\nAt line %d, column %d:\n\n",
|
|
||||||
msg, pe.Position.Line, col+1)
|
|
||||||
} else {
|
|
||||||
fmt.Fprintf(b, "toml: error: %s\n\nAt line %d, column %d-%d:\n\n",
|
|
||||||
msg, pe.Position.Line, col, col+pe.Position.Len)
|
|
||||||
}
|
|
||||||
if pe.Position.Line > 2 {
|
|
||||||
fmt.Fprintf(b, "% 7d | %s\n", pe.Position.Line-2, expandTab(lines[pe.Position.Line-3]))
|
|
||||||
}
|
|
||||||
if pe.Position.Line > 1 {
|
|
||||||
fmt.Fprintf(b, "% 7d | %s\n", pe.Position.Line-1, expandTab(lines[pe.Position.Line-2]))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Expand tabs, so that the ^^^s are at the correct position, but leave
|
|
||||||
/// "column 10-13" intact. Adjusting this to the visual column would be
|
|
||||||
/// better, but we don't know the tabsize of the user in their editor, which
|
|
||||||
/// can be 8, 4, 2, or something else. We can't know. So leaving it as the
|
|
||||||
/// character index is probably the "most correct".
|
|
||||||
expanded := expandTab(lines[pe.Position.Line-1])
|
|
||||||
diff := len(expanded) - len(lines[pe.Position.Line-1])
|
|
||||||
|
|
||||||
fmt.Fprintf(b, "% 7d | %s\n", pe.Position.Line, expanded)
|
|
||||||
fmt.Fprintf(b, "% 10s%s%s\n", "", strings.Repeat(" ", col+diff), strings.Repeat("^", pe.Position.Len))
|
|
||||||
return b.String()
|
|
||||||
}
|
|
||||||
|
|
||||||
// ErrorWithUsage returns the error with detailed location context and usage
|
|
||||||
// guidance.
|
|
||||||
//
|
|
||||||
// See the documentation on [ParseError].
|
|
||||||
func (pe ParseError) ErrorWithUsage() string {
|
|
||||||
m := pe.ErrorWithPosition()
|
|
||||||
if u, ok := pe.err.(interface{ Usage() string }); ok && u.Usage() != "" {
|
|
||||||
lines := strings.Split(strings.TrimSpace(u.Usage()), "\n")
|
|
||||||
for i := range lines {
|
|
||||||
if lines[i] != "" {
|
|
||||||
lines[i] = " " + lines[i]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return m + "Error help:\n\n" + strings.Join(lines, "\n") + "\n"
|
|
||||||
}
|
|
||||||
return m
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pe ParseError) column(lines []string) int {
|
|
||||||
var pos, col int
|
|
||||||
for i := range lines {
|
|
||||||
ll := len(lines[i]) + 1 // +1 for the removed newline
|
|
||||||
if pos+ll >= pe.Position.Start {
|
|
||||||
col = pe.Position.Start - pos
|
|
||||||
if col < 0 { // Should never happen, but just in case.
|
|
||||||
col = 0
|
|
||||||
}
|
|
||||||
break
|
|
||||||
}
|
|
||||||
pos += ll
|
|
||||||
}
|
|
||||||
|
|
||||||
return col
|
|
||||||
}
|
|
||||||
|
|
||||||
func expandTab(s string) string {
|
|
||||||
var (
|
|
||||||
b strings.Builder
|
|
||||||
l int
|
|
||||||
fill = func(n int) string {
|
|
||||||
b := make([]byte, n)
|
|
||||||
for i := range b {
|
|
||||||
b[i] = ' '
|
|
||||||
}
|
|
||||||
return string(b)
|
|
||||||
}
|
|
||||||
)
|
|
||||||
b.Grow(len(s))
|
|
||||||
for _, r := range s {
|
|
||||||
switch r {
|
|
||||||
case '\t':
|
|
||||||
tw := 8 - l%8
|
|
||||||
b.WriteString(fill(tw))
|
|
||||||
l += tw
|
|
||||||
default:
|
|
||||||
b.WriteRune(r)
|
|
||||||
l += 1
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return b.String()
|
|
||||||
}
|
|
||||||
|
|
||||||
type (
|
|
||||||
errLexControl struct{ r rune }
|
|
||||||
errLexEscape struct{ r rune }
|
|
||||||
errLexUTF8 struct{ b byte }
|
|
||||||
errParseDate struct{ v string }
|
|
||||||
errLexInlineTableNL struct{}
|
|
||||||
errLexStringNL struct{}
|
|
||||||
errParseRange struct {
|
|
||||||
i any // int or float
|
|
||||||
size string // "int64", "uint16", etc.
|
|
||||||
}
|
|
||||||
errUnsafeFloat struct {
|
|
||||||
i interface{} // float32 or float64
|
|
||||||
size string // "float32" or "float64"
|
|
||||||
}
|
|
||||||
errParseDuration struct{ d string }
|
|
||||||
)
|
|
||||||
|
|
||||||
func (e errLexControl) Error() string {
|
|
||||||
return fmt.Sprintf("TOML files cannot contain control characters: '0x%02x'", e.r)
|
|
||||||
}
|
|
||||||
func (e errLexControl) Usage() string { return "" }
|
|
||||||
|
|
||||||
func (e errLexEscape) Error() string { return fmt.Sprintf(`invalid escape in string '\%c'`, e.r) }
|
|
||||||
func (e errLexEscape) Usage() string { return usageEscape }
|
|
||||||
func (e errLexUTF8) Error() string { return fmt.Sprintf("invalid UTF-8 byte: 0x%02x", e.b) }
|
|
||||||
func (e errLexUTF8) Usage() string { return "" }
|
|
||||||
func (e errParseDate) Error() string { return fmt.Sprintf("invalid datetime: %q", e.v) }
|
|
||||||
func (e errParseDate) Usage() string { return usageDate }
|
|
||||||
func (e errLexInlineTableNL) Error() string { return "newlines not allowed within inline tables" }
|
|
||||||
func (e errLexInlineTableNL) Usage() string { return usageInlineNewline }
|
|
||||||
func (e errLexStringNL) Error() string { return "strings cannot contain newlines" }
|
|
||||||
func (e errLexStringNL) Usage() string { return usageStringNewline }
|
|
||||||
func (e errParseRange) Error() string { return fmt.Sprintf("%v is out of range for %s", e.i, e.size) }
|
|
||||||
func (e errParseRange) Usage() string { return usageIntOverflow }
|
|
||||||
func (e errUnsafeFloat) Error() string {
|
|
||||||
return fmt.Sprintf("%v is out of the safe %s range", e.i, e.size)
|
|
||||||
}
|
|
||||||
func (e errUnsafeFloat) Usage() string { return usageUnsafeFloat }
|
|
||||||
func (e errParseDuration) Error() string { return fmt.Sprintf("invalid duration: %q", e.d) }
|
|
||||||
func (e errParseDuration) Usage() string { return usageDuration }
|
|
||||||
|
|
||||||
const usageEscape = `
|
|
||||||
A '\' inside a "-delimited string is interpreted as an escape character.
|
|
||||||
|
|
||||||
The following escape sequences are supported:
|
|
||||||
\b, \t, \n, \f, \r, \", \\, \uXXXX, and \UXXXXXXXX
|
|
||||||
|
|
||||||
To prevent a '\' from being recognized as an escape character, use either:
|
|
||||||
|
|
||||||
- a ' or '''-delimited string; escape characters aren't processed in them; or
|
|
||||||
- write two backslashes to get a single backslash: '\\'.
|
|
||||||
|
|
||||||
If you're trying to add a Windows path (e.g. "C:\Users\martin") then using '/'
|
|
||||||
instead of '\' will usually also work: "C:/Users/martin".
|
|
||||||
`
|
|
||||||
|
|
||||||
const usageInlineNewline = `
|
|
||||||
Inline tables must always be on a single line:
|
|
||||||
|
|
||||||
table = {key = 42, second = 43}
|
|
||||||
|
|
||||||
It is invalid to split them over multiple lines like so:
|
|
||||||
|
|
||||||
# INVALID
|
|
||||||
table = {
|
|
||||||
key = 42,
|
|
||||||
second = 43
|
|
||||||
}
|
|
||||||
|
|
||||||
Use regular for this:
|
|
||||||
|
|
||||||
[table]
|
|
||||||
key = 42
|
|
||||||
second = 43
|
|
||||||
`
|
|
||||||
|
|
||||||
const usageStringNewline = `
|
|
||||||
Strings must always be on a single line, and cannot span more than one line:
|
|
||||||
|
|
||||||
# INVALID
|
|
||||||
string = "Hello,
|
|
||||||
world!"
|
|
||||||
|
|
||||||
Instead use """ or ''' to split strings over multiple lines:
|
|
||||||
|
|
||||||
string = """Hello,
|
|
||||||
world!"""
|
|
||||||
`
|
|
||||||
|
|
||||||
const usageIntOverflow = `
|
|
||||||
This number is too large; this may be an error in the TOML, but it can also be a
|
|
||||||
bug in the program that uses too small of an integer.
|
|
||||||
|
|
||||||
The maximum and minimum values are:
|
|
||||||
|
|
||||||
size │ lowest │ highest
|
|
||||||
───────┼────────────────┼──────────────
|
|
||||||
int8 │ -128 │ 127
|
|
||||||
int16 │ -32,768 │ 32,767
|
|
||||||
int32 │ -2,147,483,648 │ 2,147,483,647
|
|
||||||
int64 │ -9.2 × 10¹⁷ │ 9.2 × 10¹⁷
|
|
||||||
uint8 │ 0 │ 255
|
|
||||||
uint16 │ 0 │ 65,535
|
|
||||||
uint32 │ 0 │ 4,294,967,295
|
|
||||||
uint64 │ 0 │ 1.8 × 10¹⁸
|
|
||||||
|
|
||||||
int refers to int32 on 32-bit systems and int64 on 64-bit systems.
|
|
||||||
`
|
|
||||||
|
|
||||||
const usageUnsafeFloat = `
|
|
||||||
This number is outside of the "safe" range for floating point numbers; whole
|
|
||||||
(non-fractional) numbers outside the below range can not always be represented
|
|
||||||
accurately in a float, leading to some loss of accuracy.
|
|
||||||
|
|
||||||
Explicitly mark a number as a fractional unit by adding ".0", which will incur
|
|
||||||
some loss of accuracy; for example:
|
|
||||||
|
|
||||||
f = 2_000_000_000.0
|
|
||||||
|
|
||||||
Accuracy ranges:
|
|
||||||
|
|
||||||
float32 = 16,777,215
|
|
||||||
float64 = 9,007,199,254,740,991
|
|
||||||
`
|
|
||||||
|
|
||||||
const usageDuration = `
|
|
||||||
A duration must be as "number<unit>", without any spaces. Valid units are:
|
|
||||||
|
|
||||||
ns nanoseconds (billionth of a second)
|
|
||||||
us, µs microseconds (millionth of a second)
|
|
||||||
ms milliseconds (thousands of a second)
|
|
||||||
s seconds
|
|
||||||
m minutes
|
|
||||||
h hours
|
|
||||||
|
|
||||||
You can combine multiple units; for example "5m10s" for 5 minutes and 10
|
|
||||||
seconds.
|
|
||||||
`
|
|
||||||
|
|
||||||
const usageDate = `
|
|
||||||
A TOML datetime must be in one of the following formats:
|
|
||||||
|
|
||||||
2006-01-02T15:04:05Z07:00 Date and time, with timezone.
|
|
||||||
2006-01-02T15:04:05 Date and time, but without timezone.
|
|
||||||
2006-01-02 Date without a time or timezone.
|
|
||||||
15:04:05 Just a time, without any timezone.
|
|
||||||
|
|
||||||
Seconds may optionally have a fraction, up to nanosecond precision:
|
|
||||||
|
|
||||||
15:04:05.123
|
|
||||||
15:04:05.856018510
|
|
||||||
`
|
|
||||||
|
|
||||||
// TOML 1.1:
|
|
||||||
// The seconds part in times is optional, and may be omitted:
|
|
||||||
// 2006-01-02T15:04Z07:00
|
|
||||||
// 2006-01-02T15:04
|
|
||||||
// 15:04
|
|
||||||
-36
@@ -1,36 +0,0 @@
|
|||||||
package internal
|
|
||||||
|
|
||||||
import "time"
|
|
||||||
|
|
||||||
// Timezones used for local datetime, date, and time TOML types.
|
|
||||||
//
|
|
||||||
// The exact way times and dates without a timezone should be interpreted is not
|
|
||||||
// well-defined in the TOML specification and left to the implementation. These
|
|
||||||
// defaults to current local timezone offset of the computer, but this can be
|
|
||||||
// changed by changing these variables before decoding.
|
|
||||||
//
|
|
||||||
// TODO:
|
|
||||||
// Ideally we'd like to offer people the ability to configure the used timezone
|
|
||||||
// by setting Decoder.Timezone and Encoder.Timezone; however, this is a bit
|
|
||||||
// tricky: the reason we use three different variables for this is to support
|
|
||||||
// round-tripping – without these specific TZ names we wouldn't know which
|
|
||||||
// format to use.
|
|
||||||
//
|
|
||||||
// There isn't a good way to encode this right now though, and passing this sort
|
|
||||||
// of information also ties in to various related issues such as string format
|
|
||||||
// encoding, encoding of comments, etc.
|
|
||||||
//
|
|
||||||
// So, for the time being, just put this in internal until we can write a good
|
|
||||||
// comprehensive API for doing all of this.
|
|
||||||
//
|
|
||||||
// The reason they're exported is because they're referred from in e.g.
|
|
||||||
// internal/tag.
|
|
||||||
//
|
|
||||||
// Note that this behaviour is valid according to the TOML spec as the exact
|
|
||||||
// behaviour is left up to implementations.
|
|
||||||
var (
|
|
||||||
localOffset = func() int { _, o := time.Now().Zone(); return o }()
|
|
||||||
LocalDatetime = time.FixedZone("datetime-local", localOffset)
|
|
||||||
LocalDate = time.FixedZone("date-local", localOffset)
|
|
||||||
LocalTime = time.FixedZone("time-local", localOffset)
|
|
||||||
)
|
|
||||||
-1281
File diff suppressed because it is too large.
Load diff
-148
@@ -1,148 +0,0 @@
|
|||||||
package toml
|
|
||||||
|
|
||||||
import (
|
|
||||||
"strings"
|
|
||||||
)
|
|
||||||
|
|
||||||
// MetaData allows access to meta information about TOML data that's not
|
|
||||||
// accessible otherwise.
|
|
||||||
//
|
|
||||||
// It allows checking if a key is defined in the TOML data, whether any keys
|
|
||||||
// were undecoded, and the TOML type of a key.
|
|
||||||
type MetaData struct {
|
|
||||||
context Key // Used only during decoding.
|
|
||||||
|
|
||||||
keyInfo map[string]keyInfo
|
|
||||||
mapping map[string]any
|
|
||||||
keys []Key
|
|
||||||
decoded map[string]struct{}
|
|
||||||
data []byte // Input file; for errors.
|
|
||||||
}
|
|
||||||
|
|
||||||
// IsDefined reports if the key exists in the TOML data.
|
|
||||||
//
|
|
||||||
// The key should be specified hierarchically, for example to access the TOML
|
|
||||||
// key "a.b.c" you would use IsDefined("a", "b", "c"). Keys are case sensitive.
|
|
||||||
//
|
|
||||||
// Returns false for an empty key.
|
|
||||||
func (md *MetaData) IsDefined(key ...string) bool {
|
|
||||||
if len(key) == 0 {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
var (
|
|
||||||
hash map[string]any
|
|
||||||
ok bool
|
|
||||||
hashOrVal any = md.mapping
|
|
||||||
)
|
|
||||||
for _, k := range key {
|
|
||||||
if hash, ok = hashOrVal.(map[string]any); !ok {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
if hashOrVal, ok = hash[k]; !ok {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
// Type returns a string representation of the type of the key specified.
|
|
||||||
//
|
|
||||||
// Type will return the empty string if given an empty key or a key that does
|
|
||||||
// not exist. Keys are case sensitive.
|
|
||||||
func (md *MetaData) Type(key ...string) string {
|
|
||||||
if ki, ok := md.keyInfo[Key(key).String()]; ok {
|
|
||||||
return ki.tomlType.typeString()
|
|
||||||
}
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
// Keys returns a slice of every key in the TOML data, including key groups.
|
|
||||||
//
|
|
||||||
// Each key is itself a slice, where the first element is the top of the
|
|
||||||
// hierarchy and the last is the most specific. The list will have the same
|
|
||||||
// order as the keys appeared in the TOML data.
|
|
||||||
//
|
|
||||||
// All keys returned are non-empty.
|
|
||||||
func (md *MetaData) Keys() []Key {
|
|
||||||
return md.keys
|
|
||||||
}
|
|
||||||
|
|
||||||
// Undecoded returns all keys that have not been decoded in the order in which
|
|
||||||
// they appear in the original TOML document.
|
|
||||||
//
|
|
||||||
// This includes keys that haven't been decoded because of a [Primitive] value.
|
|
||||||
// Once the Primitive value is decoded, the keys will be considered decoded.
|
|
||||||
//
|
|
||||||
// Also note that decoding into an empty interface will result in no decoding,
|
|
||||||
// and so no keys will be considered decoded.
|
|
||||||
//
|
|
||||||
// In this sense, the Undecoded keys correspond to keys in the TOML document
|
|
||||||
// that do not have a concrete type in your representation.
|
|
||||||
func (md *MetaData) Undecoded() []Key {
|
|
||||||
undecoded := make([]Key, 0, len(md.keys))
|
|
||||||
for _, key := range md.keys {
|
|
||||||
if _, ok := md.decoded[key.String()]; !ok {
|
|
||||||
undecoded = append(undecoded, key)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return undecoded
|
|
||||||
}
|
|
||||||
|
|
||||||
// Key represents any TOML key, including key groups. Use [MetaData.Keys] to get
|
|
||||||
// values of this type.
|
|
||||||
type Key []string
|
|
||||||
|
|
||||||
func (k Key) String() string {
|
|
||||||
// This is called quite often, so it's a bit funky to make it faster.
|
|
||||||
var b strings.Builder
|
|
||||||
b.Grow(len(k) * 25)
|
|
||||||
outer:
|
|
||||||
for i, kk := range k {
|
|
||||||
if i > 0 {
|
|
||||||
b.WriteByte('.')
|
|
||||||
}
|
|
||||||
if kk == "" {
|
|
||||||
b.WriteString(`""`)
|
|
||||||
} else {
|
|
||||||
for _, r := range kk {
|
|
||||||
// "Inline" isBareKeyChar
|
|
||||||
if !((r >= 'A' && r <= 'Z') || (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || r == '_' || r == '-') {
|
|
||||||
b.WriteByte('"')
|
|
||||||
b.WriteString(dblQuotedReplacer.Replace(kk))
|
|
||||||
b.WriteByte('"')
|
|
||||||
continue outer
|
|
||||||
}
|
|
||||||
}
|
|
||||||
b.WriteString(kk)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return b.String()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (k Key) maybeQuoted(i int) string {
|
|
||||||
if k[i] == "" {
|
|
||||||
return `""`
|
|
||||||
}
|
|
||||||
for _, r := range k[i] {
|
|
||||||
if (r >= 'A' && r <= 'Z') || (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || r == '_' || r == '-' {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
return `"` + dblQuotedReplacer.Replace(k[i]) + `"`
|
|
||||||
}
|
|
||||||
return k[i]
|
|
||||||
}
|
|
||||||
|
|
||||||
// Like append(), but only increase the cap by 1.
|
|
||||||
func (k Key) add(piece string) Key {
|
|
||||||
if cap(k) > len(k) {
|
|
||||||
return append(k, piece)
|
|
||||||
}
|
|
||||||
newKey := make(Key, len(k)+1)
|
|
||||||
copy(newKey, k)
|
|
||||||
newKey[len(k)] = piece
|
|
||||||
return newKey
|
|
||||||
}
|
|
||||||
|
|
||||||
func (k Key) parent() Key { return k[:len(k)-1] } // all except the last piece.
|
|
||||||
func (k Key) last() string { return k[len(k)-1] } // last piece of this key.
|
|
||||||
-844
@@ -1,844 +0,0 @@
|
|||||||
package toml
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"math"
|
|
||||||
"os"
|
|
||||||
"strconv"
|
|
||||||
"strings"
|
|
||||||
"time"
|
|
||||||
"unicode/utf8"
|
|
||||||
|
|
||||||
"github.com/BurntSushi/toml/internal"
|
|
||||||
)
|
|
||||||
|
|
||||||
type parser struct {
|
|
||||||
lx *lexer
|
|
||||||
context Key // Full key for the current hash in scope.
|
|
||||||
currentKey string // Base key name for everything except hashes.
|
|
||||||
pos Position // Current position in the TOML file.
|
|
||||||
tomlNext bool
|
|
||||||
|
|
||||||
ordered []Key // List of keys in the order that they appear in the TOML data.
|
|
||||||
|
|
||||||
keyInfo map[string]keyInfo // Map keyname → info about the TOML key.
|
|
||||||
mapping map[string]any // Map keyname → key value.
|
|
||||||
implicits map[string]struct{} // Record implicit keys (e.g. "key.group.names").
|
|
||||||
}
|
|
||||||
|
|
||||||
type keyInfo struct {
|
|
||||||
pos Position
|
|
||||||
tomlType tomlType
|
|
||||||
}
|
|
||||||
|
|
||||||
func parse(data string) (p *parser, err error) {
|
|
||||||
_, tomlNext := os.LookupEnv("BURNTSUSHI_TOML_110")
|
|
||||||
|
|
||||||
defer func() {
|
|
||||||
if r := recover(); r != nil {
|
|
||||||
if pErr, ok := r.(ParseError); ok {
|
|
||||||
pErr.input = data
|
|
||||||
err = pErr
|
|
||||||
return
|
|
||||||
}
|
|
||||||
panic(r)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
// Read over BOM; do this here as the lexer calls utf8.DecodeRuneInString()
|
|
||||||
// which mangles stuff. UTF-16 BOM isn't strictly valid, but some tools add
|
|
||||||
// it anyway.
|
|
||||||
if strings.HasPrefix(data, "\xff\xfe") || strings.HasPrefix(data, "\xfe\xff") { // UTF-16
|
|
||||||
data = data[2:]
|
|
||||||
//lint:ignore S1017 https://github.com/dominikh/go-tools/issues/1447
|
|
||||||
} else if strings.HasPrefix(data, "\xef\xbb\xbf") { // UTF-8
|
|
||||||
data = data[3:]
|
|
||||||
}
|
|
||||||
|
|
||||||
// Examine first few bytes for NULL bytes; this probably means it's a UTF-16
|
|
||||||
// file (second byte in surrogate pair being NULL). Again, do this here to
|
|
||||||
// avoid having to deal with UTF-8/16 stuff in the lexer.
|
|
||||||
ex := 6
|
|
||||||
if len(data) < 6 {
|
|
||||||
ex = len(data)
|
|
||||||
}
|
|
||||||
if i := strings.IndexRune(data[:ex], 0); i > -1 {
|
|
||||||
return nil, ParseError{
|
|
||||||
Message: "files cannot contain NULL bytes; probably using UTF-16; TOML files must be UTF-8",
|
|
||||||
Position: Position{Line: 1, Start: i, Len: 1},
|
|
||||||
Line: 1,
|
|
||||||
input: data,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
p = &parser{
|
|
||||||
keyInfo: make(map[string]keyInfo),
|
|
||||||
mapping: make(map[string]any),
|
|
||||||
lx: lex(data, tomlNext),
|
|
||||||
ordered: make([]Key, 0),
|
|
||||||
implicits: make(map[string]struct{}),
|
|
||||||
tomlNext: tomlNext,
|
|
||||||
}
|
|
||||||
for {
|
|
||||||
item := p.next()
|
|
||||||
if item.typ == itemEOF {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
p.topLevel(item)
|
|
||||||
}
|
|
||||||
|
|
||||||
return p, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *parser) panicErr(it item, err error) {
|
|
||||||
panic(ParseError{
|
|
||||||
err: err,
|
|
||||||
Position: it.pos,
|
|
||||||
Line: it.pos.Len,
|
|
||||||
LastKey: p.current(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *parser) panicItemf(it item, format string, v ...any) {
|
|
||||||
panic(ParseError{
|
|
||||||
Message: fmt.Sprintf(format, v...),
|
|
||||||
Position: it.pos,
|
|
||||||
Line: it.pos.Len,
|
|
||||||
LastKey: p.current(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *parser) panicf(format string, v ...any) {
|
|
||||||
panic(ParseError{
|
|
||||||
Message: fmt.Sprintf(format, v...),
|
|
||||||
Position: p.pos,
|
|
||||||
Line: p.pos.Line,
|
|
||||||
LastKey: p.current(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *parser) next() item {
|
|
||||||
it := p.lx.nextItem()
|
|
||||||
//fmt.Printf("ITEM %-18s line %-3d │ %q\n", it.typ, it.pos.Line, it.val)
|
|
||||||
if it.typ == itemError {
|
|
||||||
if it.err != nil {
|
|
||||||
panic(ParseError{
|
|
||||||
Position: it.pos,
|
|
||||||
Line: it.pos.Line,
|
|
||||||
LastKey: p.current(),
|
|
||||||
err: it.err,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
p.panicItemf(it, "%s", it.val)
|
|
||||||
}
|
|
||||||
return it
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *parser) nextPos() item {
|
|
||||||
it := p.next()
|
|
||||||
p.pos = it.pos
|
|
||||||
return it
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *parser) bug(format string, v ...any) {
|
|
||||||
panic(fmt.Sprintf("BUG: "+format+"\n\n", v...))
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *parser) expect(typ itemType) item {
|
|
||||||
it := p.next()
|
|
||||||
p.assertEqual(typ, it.typ)
|
|
||||||
return it
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *parser) assertEqual(expected, got itemType) {
|
|
||||||
if expected != got {
|
|
||||||
p.bug("Expected '%s' but got '%s'.", expected, got)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *parser) topLevel(item item) {
|
|
||||||
switch item.typ {
|
|
||||||
case itemCommentStart: // # ..
|
|
||||||
p.expect(itemText)
|
|
||||||
case itemTableStart: // [ .. ]
|
|
||||||
name := p.nextPos()
|
|
||||||
|
|
||||||
var key Key
|
|
||||||
for ; name.typ != itemTableEnd && name.typ != itemEOF; name = p.next() {
|
|
||||||
key = append(key, p.keyString(name))
|
|
||||||
}
|
|
||||||
p.assertEqual(itemTableEnd, name.typ)
|
|
||||||
|
|
||||||
p.addContext(key, false)
|
|
||||||
p.setType("", tomlHash, item.pos)
|
|
||||||
p.ordered = append(p.ordered, key)
|
|
||||||
case itemArrayTableStart: // [[ .. ]]
|
|
||||||
name := p.nextPos()
|
|
||||||
|
|
||||||
var key Key
|
|
||||||
for ; name.typ != itemArrayTableEnd && name.typ != itemEOF; name = p.next() {
|
|
||||||
key = append(key, p.keyString(name))
|
|
||||||
}
|
|
||||||
p.assertEqual(itemArrayTableEnd, name.typ)
|
|
||||||
|
|
||||||
p.addContext(key, true)
|
|
||||||
p.setType("", tomlArrayHash, item.pos)
|
|
||||||
p.ordered = append(p.ordered, key)
|
|
||||||
case itemKeyStart: // key = ..
|
|
||||||
outerContext := p.context
|
|
||||||
/// Read all the key parts (e.g. 'a' and 'b' in 'a.b')
|
|
||||||
k := p.nextPos()
|
|
||||||
var key Key
|
|
||||||
for ; k.typ != itemKeyEnd && k.typ != itemEOF; k = p.next() {
|
|
||||||
key = append(key, p.keyString(k))
|
|
||||||
}
|
|
||||||
p.assertEqual(itemKeyEnd, k.typ)
|
|
||||||
|
|
||||||
/// The current key is the last part.
|
|
||||||
p.currentKey = key.last()
|
|
||||||
|
|
||||||
/// All the other parts (if any) are the context; need to set each part
|
|
||||||
/// as implicit.
|
|
||||||
context := key.parent()
|
|
||||||
for i := range context {
|
|
||||||
p.addImplicitContext(append(p.context, context[i:i+1]...))
|
|
||||||
}
|
|
||||||
p.ordered = append(p.ordered, p.context.add(p.currentKey))
|
|
||||||
|
|
||||||
/// Set value.
|
|
||||||
vItem := p.next()
|
|
||||||
val, typ := p.value(vItem, false)
|
|
||||||
p.setValue(p.currentKey, val)
|
|
||||||
p.setType(p.currentKey, typ, vItem.pos)
|
|
||||||
|
|
||||||
/// Remove the context we added (preserving any context from [tbl] lines).
|
|
||||||
p.context = outerContext
|
|
||||||
p.currentKey = ""
|
|
||||||
default:
|
|
||||||
p.bug("Unexpected type at top level: %s", item.typ)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Gets a string for a key (or part of a key in a table name).
|
|
||||||
func (p *parser) keyString(it item) string {
|
|
||||||
switch it.typ {
|
|
||||||
case itemText:
|
|
||||||
return it.val
|
|
||||||
case itemString, itemStringEsc, itemMultilineString,
|
|
||||||
itemRawString, itemRawMultilineString:
|
|
||||||
s, _ := p.value(it, false)
|
|
||||||
return s.(string)
|
|
||||||
default:
|
|
||||||
p.bug("Unexpected key type: %s", it.typ)
|
|
||||||
}
|
|
||||||
panic("unreachable")
|
|
||||||
}
|
|
||||||
|
|
||||||
var datetimeRepl = strings.NewReplacer(
|
|
||||||
"z", "Z",
|
|
||||||
"t", "T",
|
|
||||||
" ", "T")
|
|
||||||
|
|
||||||
// value translates an expected value from the lexer into a Go value wrapped
|
|
||||||
// as an empty interface.
|
|
||||||
func (p *parser) value(it item, parentIsArray bool) (any, tomlType) {
|
|
||||||
switch it.typ {
|
|
||||||
case itemString:
|
|
||||||
return it.val, p.typeOfPrimitive(it)
|
|
||||||
case itemStringEsc:
|
|
||||||
return p.replaceEscapes(it, it.val), p.typeOfPrimitive(it)
|
|
||||||
case itemMultilineString:
|
|
||||||
return p.replaceEscapes(it, p.stripEscapedNewlines(stripFirstNewline(it.val))), p.typeOfPrimitive(it)
|
|
||||||
case itemRawString:
|
|
||||||
return it.val, p.typeOfPrimitive(it)
|
|
||||||
case itemRawMultilineString:
|
|
||||||
return stripFirstNewline(it.val), p.typeOfPrimitive(it)
|
|
||||||
case itemInteger:
|
|
||||||
return p.valueInteger(it)
|
|
||||||
case itemFloat:
|
|
||||||
return p.valueFloat(it)
|
|
||||||
case itemBool:
|
|
||||||
switch it.val {
|
|
||||||
case "true":
|
|
||||||
return true, p.typeOfPrimitive(it)
|
|
||||||
case "false":
|
|
||||||
return false, p.typeOfPrimitive(it)
|
|
||||||
default:
|
|
||||||
p.bug("Expected boolean value, but got '%s'.", it.val)
|
|
||||||
}
|
|
||||||
case itemDatetime:
|
|
||||||
return p.valueDatetime(it)
|
|
||||||
case itemArray:
|
|
||||||
return p.valueArray(it)
|
|
||||||
case itemInlineTableStart:
|
|
||||||
return p.valueInlineTable(it, parentIsArray)
|
|
||||||
default:
|
|
||||||
p.bug("Unexpected value type: %s", it.typ)
|
|
||||||
}
|
|
||||||
panic("unreachable")
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *parser) valueInteger(it item) (any, tomlType) {
|
|
||||||
if !numUnderscoresOK(it.val) {
|
|
||||||
p.panicItemf(it, "Invalid integer %q: underscores must be surrounded by digits", it.val)
|
|
||||||
}
|
|
||||||
if numHasLeadingZero(it.val) {
|
|
||||||
p.panicItemf(it, "Invalid integer %q: cannot have leading zeroes", it.val)
|
|
||||||
}
|
|
||||||
|
|
||||||
num, err := strconv.ParseInt(it.val, 0, 64)
|
|
||||||
if err != nil {
|
|
||||||
// Distinguish integer values. Normally, it'd be a bug if the lexer
|
|
||||||
// provides an invalid integer, but it's possible that the number is
|
|
||||||
// out of range of valid values (which the lexer cannot determine).
|
|
||||||
// So mark the former as a bug but the latter as a legitimate user
|
|
||||||
// error.
|
|
||||||
if e, ok := err.(*strconv.NumError); ok && e.Err == strconv.ErrRange {
|
|
||||||
p.panicErr(it, errParseRange{i: it.val, size: "int64"})
|
|
||||||
} else {
|
|
||||||
p.bug("Expected integer value, but got '%s'.", it.val)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return num, p.typeOfPrimitive(it)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *parser) valueFloat(it item) (any, tomlType) {
|
|
||||||
parts := strings.FieldsFunc(it.val, func(r rune) bool {
|
|
||||||
switch r {
|
|
||||||
case '.', 'e', 'E':
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
})
|
|
||||||
for _, part := range parts {
|
|
||||||
if !numUnderscoresOK(part) {
|
|
||||||
p.panicItemf(it, "Invalid float %q: underscores must be surrounded by digits", it.val)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if len(parts) > 0 && numHasLeadingZero(parts[0]) {
|
|
||||||
p.panicItemf(it, "Invalid float %q: cannot have leading zeroes", it.val)
|
|
||||||
}
|
|
||||||
if !numPeriodsOK(it.val) {
|
|
||||||
// As a special case, numbers like '123.' or '1.e2',
|
|
||||||
// which are valid as far as Go/strconv are concerned,
|
|
||||||
// must be rejected because TOML says that a fractional
|
|
||||||
// part consists of '.' followed by 1+ digits.
|
|
||||||
p.panicItemf(it, "Invalid float %q: '.' must be followed by one or more digits", it.val)
|
|
||||||
}
|
|
||||||
val := strings.Replace(it.val, "_", "", -1)
|
|
||||||
signbit := false
|
|
||||||
if val == "+nan" || val == "-nan" {
|
|
||||||
signbit = val == "-nan"
|
|
||||||
val = "nan"
|
|
||||||
}
|
|
||||||
num, err := strconv.ParseFloat(val, 64)
|
|
||||||
if err != nil {
|
|
||||||
if e, ok := err.(*strconv.NumError); ok && e.Err == strconv.ErrRange {
|
|
||||||
p.panicErr(it, errParseRange{i: it.val, size: "float64"})
|
|
||||||
} else {
|
|
||||||
p.panicItemf(it, "Invalid float value: %q", it.val)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if signbit {
|
|
||||||
num = math.Copysign(num, -1)
|
|
||||||
}
|
|
||||||
return num, p.typeOfPrimitive(it)
|
|
||||||
}
|
|
||||||
|
|
||||||
var dtTypes = []struct {
|
|
||||||
fmt string
|
|
||||||
zone *time.Location
|
|
||||||
next bool
|
|
||||||
}{
|
|
||||||
{time.RFC3339Nano, time.Local, false},
|
|
||||||
{"2006-01-02T15:04:05.999999999", internal.LocalDatetime, false},
|
|
||||||
{"2006-01-02", internal.LocalDate, false},
|
|
||||||
{"15:04:05.999999999", internal.LocalTime, false},
|
|
||||||
|
|
||||||
// tomlNext
|
|
||||||
{"2006-01-02T15:04Z07:00", time.Local, true},
|
|
||||||
{"2006-01-02T15:04", internal.LocalDatetime, true},
|
|
||||||
{"15:04", internal.LocalTime, true},
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *parser) valueDatetime(it item) (any, tomlType) {
|
|
||||||
it.val = datetimeRepl.Replace(it.val)
|
|
||||||
var (
|
|
||||||
t time.Time
|
|
||||||
ok bool
|
|
||||||
err error
|
|
||||||
)
|
|
||||||
for _, dt := range dtTypes {
|
|
||||||
if dt.next && !p.tomlNext {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
t, err = time.ParseInLocation(dt.fmt, it.val, dt.zone)
|
|
||||||
if err == nil {
|
|
||||||
if missingLeadingZero(it.val, dt.fmt) {
|
|
||||||
p.panicErr(it, errParseDate{it.val})
|
|
||||||
}
|
|
||||||
ok = true
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if !ok {
|
|
||||||
p.panicErr(it, errParseDate{it.val})
|
|
||||||
}
|
|
||||||
return t, p.typeOfPrimitive(it)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Go's time.Parse() will accept numbers without a leading zero; there isn't any
|
|
||||||
// way to require it. https://github.com/golang/go/issues/29911
|
|
||||||
//
|
|
||||||
// Depend on the fact that the separators (- and :) should always be at the same
|
|
||||||
// location.
|
|
||||||
func missingLeadingZero(d, l string) bool {
|
|
||||||
for i, c := range []byte(l) {
|
|
||||||
if c == '.' || c == 'Z' {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
if (c < '0' || c > '9') && d[i] != c {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *parser) valueArray(it item) (any, tomlType) {
|
|
||||||
p.setType(p.currentKey, tomlArray, it.pos)
|
|
||||||
|
|
||||||
var (
|
|
||||||
// Initialize to a non-nil slice to make it consistent with how S = []
|
|
||||||
// decodes into a non-nil slice inside something like struct { S
|
|
||||||
// []string }. See #338
|
|
||||||
array = make([]any, 0, 2)
|
|
||||||
)
|
|
||||||
for it = p.next(); it.typ != itemArrayEnd; it = p.next() {
|
|
||||||
if it.typ == itemCommentStart {
|
|
||||||
p.expect(itemText)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
val, typ := p.value(it, true)
|
|
||||||
array = append(array, val)
|
|
||||||
|
|
||||||
// XXX: type isn't used here, we need it to record the accurate type
|
|
||||||
// information.
|
|
||||||
//
|
|
||||||
// Not entirely sure how to best store this; could use "key[0]",
|
|
||||||
// "key[1]" notation, or maybe store it on the Array type?
|
|
||||||
_ = typ
|
|
||||||
}
|
|
||||||
return array, tomlArray
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *parser) valueInlineTable(it item, parentIsArray bool) (any, tomlType) {
|
|
||||||
var (
|
|
||||||
topHash = make(map[string]any)
|
|
||||||
outerContext = p.context
|
|
||||||
outerKey = p.currentKey
|
|
||||||
)
|
|
||||||
|
|
||||||
p.context = append(p.context, p.currentKey)
|
|
||||||
prevContext := p.context
|
|
||||||
p.currentKey = ""
|
|
||||||
|
|
||||||
p.addImplicit(p.context)
|
|
||||||
p.addContext(p.context, parentIsArray)
|
|
||||||
|
|
||||||
/// Loop over all table key/value pairs.
|
|
||||||
for it := p.next(); it.typ != itemInlineTableEnd; it = p.next() {
|
|
||||||
if it.typ == itemCommentStart {
|
|
||||||
p.expect(itemText)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Read all key parts.
|
|
||||||
k := p.nextPos()
|
|
||||||
var key Key
|
|
||||||
for ; k.typ != itemKeyEnd && k.typ != itemEOF; k = p.next() {
|
|
||||||
key = append(key, p.keyString(k))
|
|
||||||
}
|
|
||||||
p.assertEqual(itemKeyEnd, k.typ)
|
|
||||||
|
|
||||||
/// The current key is the last part.
|
|
||||||
p.currentKey = key.last()
|
|
||||||
|
|
||||||
/// All the other parts (if any) are the context; need to set each part
|
|
||||||
/// as implicit.
|
|
||||||
context := key.parent()
|
|
||||||
for i := range context {
|
|
||||||
p.addImplicitContext(append(p.context, context[i:i+1]...))
|
|
||||||
}
|
|
||||||
p.ordered = append(p.ordered, p.context.add(p.currentKey))
|
|
||||||
|
|
||||||
/// Set the value.
|
|
||||||
val, typ := p.value(p.next(), false)
|
|
||||||
p.setValue(p.currentKey, val)
|
|
||||||
p.setType(p.currentKey, typ, it.pos)
|
|
||||||
|
|
||||||
hash := topHash
|
|
||||||
for _, c := range context {
|
|
||||||
h, ok := hash[c]
|
|
||||||
if !ok {
|
|
||||||
h = make(map[string]any)
|
|
||||||
hash[c] = h
|
|
||||||
}
|
|
||||||
hash, ok = h.(map[string]any)
|
|
||||||
if !ok {
|
|
||||||
p.panicf("%q is not a table", p.context)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
hash[p.currentKey] = val
|
|
||||||
|
|
||||||
/// Restore context.
|
|
||||||
p.context = prevContext
|
|
||||||
}
|
|
||||||
p.context = outerContext
|
|
||||||
p.currentKey = outerKey
|
|
||||||
return topHash, tomlHash
|
|
||||||
}
|
|
||||||
|
|
||||||
// numHasLeadingZero checks if this number has leading zeroes, allowing for '0',
|
|
||||||
// +/- signs, and base prefixes.
|
|
||||||
func numHasLeadingZero(s string) bool {
|
|
||||||
if len(s) > 1 && s[0] == '0' && !(s[1] == 'b' || s[1] == 'o' || s[1] == 'x') { // Allow 0b, 0o, 0x
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
if len(s) > 2 && (s[0] == '-' || s[0] == '+') && s[1] == '0' {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
// numUnderscoresOK checks whether each underscore in s is surrounded by
|
|
||||||
// characters that are not underscores.
|
|
||||||
func numUnderscoresOK(s string) bool {
|
|
||||||
switch s {
|
|
||||||
case "nan", "+nan", "-nan", "inf", "-inf", "+inf":
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
accept := false
|
|
||||||
for _, r := range s {
|
|
||||||
if r == '_' {
|
|
||||||
if !accept {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// isHexis a superset of all the permissable characters surrounding an
|
|
||||||
// underscore.
|
|
||||||
accept = isHex(r)
|
|
||||||
}
|
|
||||||
return accept
|
|
||||||
}
|
|
||||||
|
|
||||||
// numPeriodsOK checks whether every period in s is followed by a digit.
|
|
||||||
func numPeriodsOK(s string) bool {
|
|
||||||
period := false
|
|
||||||
for _, r := range s {
|
|
||||||
if period && !isDigit(r) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
period = r == '.'
|
|
||||||
}
|
|
||||||
return !period
|
|
||||||
}
|
|
||||||
|
|
||||||
// Set the current context of the parser, where the context is either a hash or
|
|
||||||
// an array of hashes, depending on the value of the `array` parameter.
|
|
||||||
//
|
|
||||||
// Establishing the context also makes sure that the key isn't a duplicate, and
|
|
||||||
// will create implicit hashes automatically.
|
|
||||||
func (p *parser) addContext(key Key, array bool) {
|
|
||||||
/// Always start at the top level and drill down for our context.
|
|
||||||
hashContext := p.mapping
|
|
||||||
keyContext := make(Key, 0, len(key)-1)
|
|
||||||
|
|
||||||
/// We only need implicit hashes for the parents.
|
|
||||||
for _, k := range key.parent() {
|
|
||||||
_, ok := hashContext[k]
|
|
||||||
keyContext = append(keyContext, k)
|
|
||||||
|
|
||||||
// No key? Make an implicit hash and move on.
|
|
||||||
if !ok {
|
|
||||||
p.addImplicit(keyContext)
|
|
||||||
hashContext[k] = make(map[string]any)
|
|
||||||
}
|
|
||||||
|
|
||||||
// If the hash context is actually an array of tables, then set
|
|
||||||
// the hash context to the last element in that array.
|
|
||||||
//
|
|
||||||
// Otherwise, it better be a table, since this MUST be a key group (by
|
|
||||||
// virtue of it not being the last element in a key).
|
|
||||||
switch t := hashContext[k].(type) {
|
|
||||||
case []map[string]any:
|
|
||||||
hashContext = t[len(t)-1]
|
|
||||||
case map[string]any:
|
|
||||||
hashContext = t
|
|
||||||
default:
|
|
||||||
p.panicf("Key '%s' was already created as a hash.", keyContext)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
p.context = keyContext
|
|
||||||
if array {
|
|
||||||
// If this is the first element for this array, then allocate a new
|
|
||||||
// list of tables for it.
|
|
||||||
k := key.last()
|
|
||||||
if _, ok := hashContext[k]; !ok {
|
|
||||||
hashContext[k] = make([]map[string]any, 0, 4)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Add a new table. But make sure the key hasn't already been used
|
|
||||||
// for something else.
|
|
||||||
if hash, ok := hashContext[k].([]map[string]any); ok {
|
|
||||||
hashContext[k] = append(hash, make(map[string]any))
|
|
||||||
} else {
|
|
||||||
p.panicf("Key '%s' was already created and cannot be used as an array.", key)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
p.setValue(key.last(), make(map[string]any))
|
|
||||||
}
|
|
||||||
p.context = append(p.context, key.last())
|
|
||||||
}
|
|
||||||
|
|
||||||
// setValue sets the given key to the given value in the current context.
|
|
||||||
// It will make sure that the key hasn't already been defined, account for
|
|
||||||
// implicit key groups.
|
|
||||||
func (p *parser) setValue(key string, value any) {
|
|
||||||
var (
|
|
||||||
tmpHash any
|
|
||||||
ok bool
|
|
||||||
hash = p.mapping
|
|
||||||
keyContext = make(Key, 0, len(p.context)+1)
|
|
||||||
)
|
|
||||||
for _, k := range p.context {
|
|
||||||
keyContext = append(keyContext, k)
|
|
||||||
if tmpHash, ok = hash[k]; !ok {
|
|
||||||
p.bug("Context for key '%s' has not been established.", keyContext)
|
|
||||||
}
|
|
||||||
switch t := tmpHash.(type) {
|
|
||||||
case []map[string]any:
|
|
||||||
// The context is a table of hashes. Pick the most recent table
|
|
||||||
// defined as the current hash.
|
|
||||||
hash = t[len(t)-1]
|
|
||||||
case map[string]any:
|
|
||||||
hash = t
|
|
||||||
default:
|
|
||||||
p.panicf("Key '%s' has already been defined.", keyContext)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
keyContext = append(keyContext, key)
|
|
||||||
|
|
||||||
if _, ok := hash[key]; ok {
|
|
||||||
// Normally redefining keys isn't allowed, but the key could have been
|
|
||||||
// defined implicitly and it's allowed to be redefined concretely. (See
|
|
||||||
// the `valid/implicit-and-explicit-after.toml` in toml-test)
|
|
||||||
//
|
|
||||||
// But we have to make sure to stop marking it as an implicit. (So that
|
|
||||||
// another redefinition provokes an error.)
|
|
||||||
//
|
|
||||||
// Note that since it has already been defined (as a hash), we don't
|
|
||||||
// want to overwrite it. So our business is done.
|
|
||||||
if p.isArray(keyContext) {
|
|
||||||
p.removeImplicit(keyContext)
|
|
||||||
hash[key] = value
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if p.isImplicit(keyContext) {
|
|
||||||
p.removeImplicit(keyContext)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
// Otherwise, we have a concrete key trying to override a previous key,
|
|
||||||
// which is *always* wrong.
|
|
||||||
p.panicf("Key '%s' has already been defined.", keyContext)
|
|
||||||
}
|
|
||||||
|
|
||||||
hash[key] = value
|
|
||||||
}
|
|
||||||
|
|
||||||
// setType sets the type of a particular value at a given key. It should be
|
|
||||||
// called immediately AFTER setValue.
|
|
||||||
//
|
|
||||||
// Note that if `key` is empty, then the type given will be applied to the
|
|
||||||
// current context (which is either a table or an array of tables).
|
|
||||||
func (p *parser) setType(key string, typ tomlType, pos Position) {
|
|
||||||
keyContext := make(Key, 0, len(p.context)+1)
|
|
||||||
keyContext = append(keyContext, p.context...)
|
|
||||||
if len(key) > 0 { // allow type setting for hashes
|
|
||||||
keyContext = append(keyContext, key)
|
|
||||||
}
|
|
||||||
// Special case to make empty keys ("" = 1) work.
|
|
||||||
// Without it it will set "" rather than `""`.
|
|
||||||
// TODO: why is this needed? And why is this only needed here?
|
|
||||||
if len(keyContext) == 0 {
|
|
||||||
keyContext = Key{""}
|
|
||||||
}
|
|
||||||
p.keyInfo[keyContext.String()] = keyInfo{tomlType: typ, pos: pos}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Implicit keys need to be created when tables are implied in "a.b.c.d = 1" and
|
|
||||||
// "[a.b.c]" (the "a", "b", and "c" hashes are never created explicitly).
|
|
||||||
func (p *parser) addImplicit(key Key) { p.implicits[key.String()] = struct{}{} }
|
|
||||||
func (p *parser) removeImplicit(key Key) { delete(p.implicits, key.String()) }
|
|
||||||
func (p *parser) isImplicit(key Key) bool { _, ok := p.implicits[key.String()]; return ok }
|
|
||||||
func (p *parser) isArray(key Key) bool { return p.keyInfo[key.String()].tomlType == tomlArray }
|
|
||||||
func (p *parser) addImplicitContext(key Key) { p.addImplicit(key); p.addContext(key, false) }
|
|
||||||
|
|
||||||
// current returns the full key name of the current context.
|
|
||||||
func (p *parser) current() string {
|
|
||||||
if len(p.currentKey) == 0 {
|
|
||||||
return p.context.String()
|
|
||||||
}
|
|
||||||
if len(p.context) == 0 {
|
|
||||||
return p.currentKey
|
|
||||||
}
|
|
||||||
return fmt.Sprintf("%s.%s", p.context, p.currentKey)
|
|
||||||
}
|
|
||||||
|
|
||||||
func stripFirstNewline(s string) string {
|
|
||||||
if len(s) > 0 && s[0] == '\n' {
|
|
||||||
return s[1:]
|
|
||||||
}
|
|
||||||
if len(s) > 1 && s[0] == '\r' && s[1] == '\n' {
|
|
||||||
return s[2:]
|
|
||||||
}
|
|
||||||
return s
|
|
||||||
}
|
|
||||||
|
|
||||||
// stripEscapedNewlines removes whitespace after line-ending backslashes in
|
|
||||||
// multiline strings.
|
|
||||||
//
|
|
||||||
// A line-ending backslash is an unescaped \ followed only by whitespace until
|
|
||||||
// the next newline. After a line-ending backslash, all whitespace is removed
|
|
||||||
// until the next non-whitespace character.
|
|
||||||
func (p *parser) stripEscapedNewlines(s string) string {
|
|
||||||
var (
|
|
||||||
b strings.Builder
|
|
||||||
i int
|
|
||||||
)
|
|
||||||
b.Grow(len(s))
|
|
||||||
for {
|
|
||||||
ix := strings.Index(s[i:], `\`)
|
|
||||||
if ix < 0 {
|
|
||||||
b.WriteString(s)
|
|
||||||
return b.String()
|
|
||||||
}
|
|
||||||
i += ix
|
|
||||||
|
|
||||||
if len(s) > i+1 && s[i+1] == '\\' {
|
|
||||||
// Escaped backslash.
|
|
||||||
i += 2
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
// Scan until the next non-whitespace.
|
|
||||||
j := i + 1
|
|
||||||
whitespaceLoop:
|
|
||||||
for ; j < len(s); j++ {
|
|
||||||
switch s[j] {
|
|
||||||
case ' ', '\t', '\r', '\n':
|
|
||||||
default:
|
|
||||||
break whitespaceLoop
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if j == i+1 {
|
|
||||||
// Not a whitespace escape.
|
|
||||||
i++
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if !strings.Contains(s[i:j], "\n") {
|
|
||||||
// This is not a line-ending backslash. (It's a bad escape sequence,
|
|
||||||
// but we can let replaceEscapes catch it.)
|
|
||||||
i++
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
b.WriteString(s[:i])
|
|
||||||
s = s[j:]
|
|
||||||
i = 0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *parser) replaceEscapes(it item, str string) string {
|
|
||||||
var (
|
|
||||||
b strings.Builder
|
|
||||||
skip = 0
|
|
||||||
)
|
|
||||||
b.Grow(len(str))
|
|
||||||
for i, c := range str {
|
|
||||||
if skip > 0 {
|
|
||||||
skip--
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if c != '\\' {
|
|
||||||
b.WriteRune(c)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
if i >= len(str) {
|
|
||||||
p.bug("Escape sequence at end of string.")
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
switch str[i+1] {
|
|
||||||
default:
|
|
||||||
p.bug("Expected valid escape code after \\, but got %q.", str[i+1])
|
|
||||||
case ' ', '\t':
|
|
||||||
p.panicItemf(it, "invalid escape: '\\%c'", str[i+1])
|
|
||||||
case 'b':
|
|
||||||
b.WriteByte(0x08)
|
|
||||||
skip = 1
|
|
||||||
case 't':
|
|
||||||
b.WriteByte(0x09)
|
|
||||||
skip = 1
|
|
||||||
case 'n':
|
|
||||||
b.WriteByte(0x0a)
|
|
||||||
skip = 1
|
|
||||||
case 'f':
|
|
||||||
b.WriteByte(0x0c)
|
|
||||||
skip = 1
|
|
||||||
case 'r':
|
|
||||||
b.WriteByte(0x0d)
|
|
||||||
skip = 1
|
|
||||||
case 'e':
|
|
||||||
if p.tomlNext {
|
|
||||||
b.WriteByte(0x1b)
|
|
||||||
skip = 1
|
|
||||||
}
|
|
||||||
case '"':
|
|
||||||
b.WriteByte(0x22)
|
|
||||||
skip = 1
|
|
||||||
case '\\':
|
|
||||||
b.WriteByte(0x5c)
|
|
||||||
skip = 1
|
|
||||||
// The lexer guarantees the correct number of characters are present;
|
|
||||||
// don't need to check here.
|
|
||||||
case 'x':
|
|
||||||
if p.tomlNext {
|
|
||||||
escaped := p.asciiEscapeToUnicode(it, str[i+2:i+4])
|
|
||||||
b.WriteRune(escaped)
|
|
||||||
skip = 3
|
|
||||||
}
|
|
||||||
case 'u':
|
|
||||||
escaped := p.asciiEscapeToUnicode(it, str[i+2:i+6])
|
|
||||||
b.WriteRune(escaped)
|
|
||||||
skip = 5
|
|
||||||
case 'U':
|
|
||||||
escaped := p.asciiEscapeToUnicode(it, str[i+2:i+10])
|
|
||||||
b.WriteRune(escaped)
|
|
||||||
skip = 9
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return b.String()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *parser) asciiEscapeToUnicode(it item, s string) rune {
|
|
||||||
hex, err := strconv.ParseUint(strings.ToLower(s), 16, 32)
|
|
||||||
if err != nil {
|
|
||||||
p.bug("Could not parse '%s' as a hexadecimal number, but the lexer claims it's OK: %s", s, err)
|
|
||||||
}
|
|
||||||
if !utf8.ValidRune(rune(hex)) {
|
|
||||||
p.panicItemf(it, "Escaped character '\\u%s' is not valid UTF-8.", s)
|
|
||||||
}
|
|
||||||
return rune(hex)
|
|
||||||
}
|
|
||||||
-238
@@ -1,238 +0,0 @@
|
|||||||
package toml
|
|
||||||
|
|
||||||
// Struct field handling is adapted from code in encoding/json:
|
|
||||||
//
|
|
||||||
// Copyright 2010 The Go Authors. All rights reserved.
|
|
||||||
// Use of this source code is governed by a BSD-style
|
|
||||||
// license that can be found in the Go distribution.
|
|
||||||
|
|
||||||
import (
|
|
||||||
"reflect"
|
|
||||||
"sort"
|
|
||||||
"sync"
|
|
||||||
)
|
|
||||||
|
|
||||||
// A field represents a single field found in a struct.
|
|
||||||
type field struct {
|
|
||||||
name string // the name of the field (`toml` tag included)
|
|
||||||
tag bool // whether field has a `toml` tag
|
|
||||||
index []int // represents the depth of an anonymous field
|
|
||||||
typ reflect.Type // the type of the field
|
|
||||||
}
|
|
||||||
|
|
||||||
// byName sorts field by name, breaking ties with depth,
|
|
||||||
// then breaking ties with "name came from toml tag", then
|
|
||||||
// breaking ties with index sequence.
|
|
||||||
type byName []field
|
|
||||||
|
|
||||||
func (x byName) Len() int { return len(x) }
|
|
||||||
func (x byName) Swap(i, j int) { x[i], x[j] = x[j], x[i] }
|
|
||||||
func (x byName) Less(i, j int) bool {
|
|
||||||
if x[i].name != x[j].name {
|
|
||||||
return x[i].name < x[j].name
|
|
||||||
}
|
|
||||||
if len(x[i].index) != len(x[j].index) {
|
|
||||||
return len(x[i].index) < len(x[j].index)
|
|
||||||
}
|
|
||||||
if x[i].tag != x[j].tag {
|
|
||||||
return x[i].tag
|
|
||||||
}
|
|
||||||
return byIndex(x).Less(i, j)
|
|
||||||
}
|
|
||||||
|
|
||||||
// byIndex sorts field by index sequence.
|
|
||||||
type byIndex []field
|
|
||||||
|
|
||||||
func (x byIndex) Len() int { return len(x) }
|
|
||||||
func (x byIndex) Swap(i, j int) { x[i], x[j] = x[j], x[i] }
|
|
||||||
func (x byIndex) Less(i, j int) bool {
|
|
||||||
for k, xik := range x[i].index {
|
|
||||||
if k >= len(x[j].index) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
if xik != x[j].index[k] {
|
|
||||||
return xik < x[j].index[k]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return len(x[i].index) < len(x[j].index)
|
|
||||||
}
|
|
||||||
|
|
||||||
// typeFields returns a list of fields that TOML should recognize for the given
|
|
||||||
// type. The algorithm is breadth-first search over the set of structs to
|
|
||||||
// include - the top struct and then any reachable anonymous structs.
|
|
||||||
func typeFields(t reflect.Type) []field {
|
|
||||||
// Anonymous fields to explore at the current level and the next.
|
|
||||||
current := []field{}
|
|
||||||
next := []field{{typ: t}}
|
|
||||||
|
|
||||||
// Count of queued names for current level and the next.
|
|
||||||
var count map[reflect.Type]int
|
|
||||||
var nextCount map[reflect.Type]int
|
|
||||||
|
|
||||||
// Types already visited at an earlier level.
|
|
||||||
visited := map[reflect.Type]bool{}
|
|
||||||
|
|
||||||
// Fields found.
|
|
||||||
var fields []field
|
|
||||||
|
|
||||||
for len(next) > 0 {
|
|
||||||
current, next = next, current[:0]
|
|
||||||
count, nextCount = nextCount, map[reflect.Type]int{}
|
|
||||||
|
|
||||||
for _, f := range current {
|
|
||||||
if visited[f.typ] {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
visited[f.typ] = true
|
|
||||||
|
|
||||||
// Scan f.typ for fields to include.
|
|
||||||
for i := 0; i < f.typ.NumField(); i++ {
|
|
||||||
sf := f.typ.Field(i)
|
|
||||||
if sf.PkgPath != "" && !sf.Anonymous { // unexported
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
opts := getOptions(sf.Tag)
|
|
||||||
if opts.skip {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
index := make([]int, len(f.index)+1)
|
|
||||||
copy(index, f.index)
|
|
||||||
index[len(f.index)] = i
|
|
||||||
|
|
||||||
ft := sf.Type
|
|
||||||
if ft.Name() == "" && ft.Kind() == reflect.Ptr {
|
|
||||||
// Follow pointer.
|
|
||||||
ft = ft.Elem()
|
|
||||||
}
|
|
||||||
|
|
||||||
// Record found field and index sequence.
|
|
||||||
if opts.name != "" || !sf.Anonymous || ft.Kind() != reflect.Struct {
|
|
||||||
tagged := opts.name != ""
|
|
||||||
name := opts.name
|
|
||||||
if name == "" {
|
|
||||||
name = sf.Name
|
|
||||||
}
|
|
||||||
fields = append(fields, field{name, tagged, index, ft})
|
|
||||||
if count[f.typ] > 1 {
|
|
||||||
// If there were multiple instances, add a second,
|
|
||||||
// so that the annihilation code will see a duplicate.
|
|
||||||
// It only cares about the distinction between 1 or 2,
|
|
||||||
// so don't bother generating any more copies.
|
|
||||||
fields = append(fields, fields[len(fields)-1])
|
|
||||||
}
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
// Record new anonymous struct to explore in next round.
|
|
||||||
nextCount[ft]++
|
|
||||||
if nextCount[ft] == 1 {
|
|
||||||
f := field{name: ft.Name(), index: index, typ: ft}
|
|
||||||
next = append(next, f)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
sort.Sort(byName(fields))
|
|
||||||
|
|
||||||
// Delete all fields that are hidden by the Go rules for embedded fields,
|
|
||||||
// except that fields with TOML tags are promoted.
|
|
||||||
|
|
||||||
// The fields are sorted in primary order of name, secondary order
|
|
||||||
// of field index length. Loop over names; for each name, delete
|
|
||||||
// hidden fields by choosing the one dominant field that survives.
|
|
||||||
out := fields[:0]
|
|
||||||
for advance, i := 0, 0; i < len(fields); i += advance {
|
|
||||||
// One iteration per name.
|
|
||||||
// Find the sequence of fields with the name of this first field.
|
|
||||||
fi := fields[i]
|
|
||||||
name := fi.name
|
|
||||||
for advance = 1; i+advance < len(fields); advance++ {
|
|
||||||
fj := fields[i+advance]
|
|
||||||
if fj.name != name {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if advance == 1 { // Only one field with this name
|
|
||||||
out = append(out, fi)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
dominant, ok := dominantField(fields[i : i+advance])
|
|
||||||
if ok {
|
|
||||||
out = append(out, dominant)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fields = out
|
|
||||||
sort.Sort(byIndex(fields))
|
|
||||||
|
|
||||||
return fields
|
|
||||||
}
|
|
||||||
|
|
||||||
// dominantField looks through the fields, all of which are known to
|
|
||||||
// have the same name, to find the single field that dominates the
|
|
||||||
// others using Go's embedding rules, modified by the presence of
|
|
||||||
// TOML tags. If there are multiple top-level fields, the boolean
|
|
||||||
// will be false: This condition is an error in Go and we skip all
|
|
||||||
// the fields.
|
|
||||||
func dominantField(fields []field) (field, bool) {
|
|
||||||
// The fields are sorted in increasing index-length order. The winner
|
|
||||||
// must therefore be one with the shortest index length. Drop all
|
|
||||||
// longer entries, which is easy: just truncate the slice.
|
|
||||||
length := len(fields[0].index)
|
|
||||||
tagged := -1 // Index of first tagged field.
|
|
||||||
for i, f := range fields {
|
|
||||||
if len(f.index) > length {
|
|
||||||
fields = fields[:i]
|
|
||||||
break
|
|
||||||
}
|
|
||||||
if f.tag {
|
|
||||||
if tagged >= 0 {
|
|
||||||
// Multiple tagged fields at the same level: conflict.
|
|
||||||
// Return no field.
|
|
||||||
return field{}, false
|
|
||||||
}
|
|
||||||
tagged = i
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if tagged >= 0 {
|
|
||||||
return fields[tagged], true
|
|
||||||
}
|
|
||||||
// All remaining fields have the same length. If there's more than one,
|
|
||||||
// we have a conflict (two fields named "X" at the same level) and we
|
|
||||||
// return no field.
|
|
||||||
if len(fields) > 1 {
|
|
||||||
return field{}, false
|
|
||||||
}
|
|
||||||
return fields[0], true
|
|
||||||
}
|
|
||||||
|
|
||||||
var fieldCache struct {
|
|
||||||
sync.RWMutex
|
|
||||||
m map[reflect.Type][]field
|
|
||||||
}
|
|
||||||
|
|
||||||
// cachedTypeFields is like typeFields but uses a cache to avoid repeated work.
|
|
||||||
func cachedTypeFields(t reflect.Type) []field {
|
|
||||||
fieldCache.RLock()
|
|
||||||
f := fieldCache.m[t]
|
|
||||||
fieldCache.RUnlock()
|
|
||||||
if f != nil {
|
|
||||||
return f
|
|
||||||
}
|
|
||||||
|
|
||||||
// Compute fields without lock.
|
|
||||||
// Might duplicate effort but won't hold other computations back.
|
|
||||||
f = typeFields(t)
|
|
||||||
if f == nil {
|
|
||||||
f = []field{}
|
|
||||||
}
|
|
||||||
|
|
||||||
fieldCache.Lock()
|
|
||||||
if fieldCache.m == nil {
|
|
||||||
fieldCache.m = map[reflect.Type][]field{}
|
|
||||||
}
|
|
||||||
fieldCache.m[t] = f
|
|
||||||
fieldCache.Unlock()
|
|
||||||
return f
|
|
||||||
}
|
|
||||||
-65
@@ -1,65 +0,0 @@
|
|||||||
package toml
|
|
||||||
|
|
||||||
// tomlType represents any Go type that corresponds to a TOML type.
|
|
||||||
// While the first draft of the TOML spec has a simplistic type system that
|
|
||||||
// probably doesn't need this level of sophistication, we seem to be militating
|
|
||||||
// toward adding real composite types.
|
|
||||||
type tomlType interface {
|
|
||||||
typeString() string
|
|
||||||
}
|
|
||||||
|
|
||||||
// typeEqual accepts any two types and returns true if they are equal.
|
|
||||||
func typeEqual(t1, t2 tomlType) bool {
|
|
||||||
if t1 == nil || t2 == nil {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
return t1.typeString() == t2.typeString()
|
|
||||||
}
|
|
||||||
|
|
||||||
func typeIsTable(t tomlType) bool {
|
|
||||||
return typeEqual(t, tomlHash) || typeEqual(t, tomlArrayHash)
|
|
||||||
}
|
|
||||||
|
|
||||||
type tomlBaseType string
|
|
||||||
|
|
||||||
func (btype tomlBaseType) typeString() string { return string(btype) }
|
|
||||||
func (btype tomlBaseType) String() string { return btype.typeString() }
|
|
||||||
|
|
||||||
var (
|
|
||||||
tomlInteger tomlBaseType = "Integer"
|
|
||||||
tomlFloat tomlBaseType = "Float"
|
|
||||||
tomlDatetime tomlBaseType = "Datetime"
|
|
||||||
tomlString tomlBaseType = "String"
|
|
||||||
tomlBool tomlBaseType = "Bool"
|
|
||||||
tomlArray tomlBaseType = "Array"
|
|
||||||
tomlHash tomlBaseType = "Hash"
|
|
||||||
tomlArrayHash tomlBaseType = "ArrayHash"
|
|
||||||
)
|
|
||||||
|
|
||||||
// typeOfPrimitive returns a tomlType of any primitive value in TOML.
|
|
||||||
// Primitive values are: Integer, Float, Datetime, String and Bool.
|
|
||||||
//
|
|
||||||
// Passing a lexer item other than the following will cause a BUG message
|
|
||||||
// to occur: itemString, itemBool, itemInteger, itemFloat, itemDatetime.
|
|
||||||
func (p *parser) typeOfPrimitive(lexItem item) tomlType {
|
|
||||||
switch lexItem.typ {
|
|
||||||
case itemInteger:
|
|
||||||
return tomlInteger
|
|
||||||
case itemFloat:
|
|
||||||
return tomlFloat
|
|
||||||
case itemDatetime:
|
|
||||||
return tomlDatetime
|
|
||||||
case itemString, itemStringEsc:
|
|
||||||
return tomlString
|
|
||||||
case itemMultilineString:
|
|
||||||
return tomlString
|
|
||||||
case itemRawString:
|
|
||||||
return tomlString
|
|
||||||
case itemRawMultilineString:
|
|
||||||
return tomlString
|
|
||||||
case itemBool:
|
|
||||||
return tomlBool
|
|
||||||
}
|
|
||||||
p.bug("Cannot infer primitive type of lex item '%s'.", lexItem)
|
|
||||||
panic("unreachable")
|
|
||||||
}
|
|
||||||
-19
@@ -1,19 +0,0 @@
|
|||||||
Copyright (C) 2012 Yasushi Saito, 2013 Foize B.V.
|
|
||||||
|
|
||||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
||||||
of this software and associated documentation files (the "Software"), to deal
|
|
||||||
in the Software without restriction, including without limitation the rights
|
|
||||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
||||||
copies of the Software, and to permit persons to whom the Software is
|
|
||||||
furnished to do so, subject to the following conditions:
|
|
||||||
|
|
||||||
The above copyright notice and this permission notice shall be included in
|
|
||||||
all copies or substantial portions of the Software.
|
|
||||||
|
|
||||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
||||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
||||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
||||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
||||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
||||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
|
||||||
THE SOFTWARE.
|
|
||||||
-113
@@ -1,113 +0,0 @@
|
|||||||
// Created by Yaz Saito on 06/15/12.
|
|
||||||
// Modified by Geert-Johan Riemer, Foize B.V.
|
|
||||||
|
|
||||||
// TODO:
|
|
||||||
// - travis CI
|
|
||||||
// - maybe add method (*Queue).Peek()
|
|
||||||
|
|
||||||
package fifo
|
|
||||||
|
|
||||||
import (
|
|
||||||
"sync"
|
|
||||||
)
|
|
||||||
|
|
||||||
const chunkSize = 64
|
|
||||||
|
|
||||||
// chunks are used to make a queue auto resizeable.
|
|
||||||
type chunk struct {
|
|
||||||
items [chunkSize]interface{} // list of queue'ed items
|
|
||||||
first, last int // positions for the first and list item in this chunk
|
|
||||||
next *chunk // pointer to the next chunk (if any)
|
|
||||||
}
|
|
||||||
|
|
||||||
// fifo queue
|
|
||||||
type Queue struct {
|
|
||||||
head, tail *chunk // chunk head and tail
|
|
||||||
count int // total amount of items in the queue
|
|
||||||
lock sync.Mutex // synchronisation lock
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewQueue creates a new and empty *fifo.Queue
|
|
||||||
func NewQueue() (q *Queue) {
|
|
||||||
initChunk := new(chunk)
|
|
||||||
q = &Queue{
|
|
||||||
head: initChunk,
|
|
||||||
tail: initChunk,
|
|
||||||
}
|
|
||||||
return q
|
|
||||||
}
|
|
||||||
|
|
||||||
// Return the number of items in the queue
|
|
||||||
func (q *Queue) Len() (length int) {
|
|
||||||
// locking to make Queue thread-safe
|
|
||||||
q.lock.Lock()
|
|
||||||
defer q.lock.Unlock()
|
|
||||||
|
|
||||||
// copy q.count and return length
|
|
||||||
length = q.count
|
|
||||||
return length
|
|
||||||
}
|
|
||||||
|
|
||||||
// Add an item to the end of the queue
|
|
||||||
func (q *Queue) Add(item interface{}) {
|
|
||||||
// locking to make Queue thread-safe
|
|
||||||
q.lock.Lock()
|
|
||||||
defer q.lock.Unlock()
|
|
||||||
|
|
||||||
// check if item is valid
|
|
||||||
if item == nil {
|
|
||||||
panic("can not add nil item to fifo queue")
|
|
||||||
}
|
|
||||||
|
|
||||||
// if the tail chunk is full, create a new one and add it to the queue.
|
|
||||||
if q.tail.last >= chunkSize {
|
|
||||||
q.tail.next = new(chunk)
|
|
||||||
q.tail = q.tail.next
|
|
||||||
}
|
|
||||||
|
|
||||||
// add item to the tail chunk at the last position
|
|
||||||
q.tail.items[q.tail.last] = item
|
|
||||||
q.tail.last++
|
|
||||||
q.count++
|
|
||||||
}
|
|
||||||
|
|
||||||
// Remove the item at the head of the queue and return it.
|
|
||||||
// Returns nil when there are no items left in queue.
|
|
||||||
func (q *Queue) Next() (item interface{}) {
|
|
||||||
// locking to make Queue thread-safe
|
|
||||||
q.lock.Lock()
|
|
||||||
defer q.lock.Unlock()
|
|
||||||
|
|
||||||
// Return nil if there are no items to return
|
|
||||||
if q.count == 0 {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
// FIXME: why would this check be required?
|
|
||||||
if q.head.first >= q.head.last {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get item from queue
|
|
||||||
item = q.head.items[q.head.first]
|
|
||||||
|
|
||||||
// increment first position and decrement queue item count
|
|
||||||
q.head.first++
|
|
||||||
q.count--
|
|
||||||
|
|
||||||
if q.head.first >= q.head.last {
|
|
||||||
// we're at the end of this chunk and we should do some maintainance
|
|
||||||
// if there are no follow up chunks then reset the current one so it can be used again.
|
|
||||||
if q.count == 0 {
|
|
||||||
q.head.first = 0
|
|
||||||
q.head.last = 0
|
|
||||||
q.head.next = nil
|
|
||||||
} else {
|
|
||||||
// set queue's head chunk to the next chunk
|
|
||||||
// old head will fall out of scope and be GC-ed
|
|
||||||
q.head = q.head.next
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// return the retrieved item
|
|
||||||
return item
|
|
||||||
}
|
|
||||||
-107
@@ -1,107 +0,0 @@
|
|||||||
## go.fifo
|
|
||||||
|
|
||||||
### Description
|
|
||||||
go.fifo provides a simple FIFO thread-safe queue.
|
|
||||||
*fifo.Queue supports pushing an item at the end with Add(), and popping an item from the front with Next().
|
|
||||||
There is no intermediate type for the stored data. Data is directly added and retrieved as type interface{}
|
|
||||||
The queue itself is implemented as a single-linked list of chunks containing max 64 items each.
|
|
||||||
|
|
||||||
### Installation
|
|
||||||
`go get github.com/foize/go.fifo`
|
|
||||||
|
|
||||||
### Usage
|
|
||||||
```go
|
|
||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/foize/go.fifo"
|
|
||||||
"fmt"
|
|
||||||
)
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
// create a new queue
|
|
||||||
numbers := fifo.NewQueue()
|
|
||||||
|
|
||||||
// add items to the queue
|
|
||||||
numbers.Add(42)
|
|
||||||
numbers.Add(123)
|
|
||||||
numbers.Add(456)
|
|
||||||
|
|
||||||
// retrieve items from the queue
|
|
||||||
fmt.Println(numbers.Next()) // 42
|
|
||||||
fmt.Println(numbers.Next()) // 123
|
|
||||||
fmt.Println(numbers.Next()) // 456
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
```go
|
|
||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/foize/go.fifo"
|
|
||||||
"fmt"
|
|
||||||
)
|
|
||||||
|
|
||||||
type thing struct {
|
|
||||||
Text string
|
|
||||||
Number int
|
|
||||||
}
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
// create a new queue
|
|
||||||
things := fifo.NewQueue()
|
|
||||||
|
|
||||||
// add items to the queue
|
|
||||||
things.Add(&thing{
|
|
||||||
Text: "one thing",
|
|
||||||
Number: 1,
|
|
||||||
})
|
|
||||||
things.Add(&thing {
|
|
||||||
Text: "another thing",
|
|
||||||
Number: 2,
|
|
||||||
})
|
|
||||||
|
|
||||||
// retrieve items from the queue
|
|
||||||
for {
|
|
||||||
// get a new item from the things queue
|
|
||||||
item := things.Next();
|
|
||||||
|
|
||||||
// check if there was an item
|
|
||||||
if item == nil {
|
|
||||||
fmt.Println("queue is empty")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// assert the type for the item
|
|
||||||
someThing := item.(*thing)
|
|
||||||
|
|
||||||
// print the fields
|
|
||||||
fmt.Println(someThing.Text)
|
|
||||||
fmt.Printf("with number: %d\n", someThing.Number)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/* output: */
|
|
||||||
// one thing
|
|
||||||
// with number: 1
|
|
||||||
// another thing
|
|
||||||
// with number: 2
|
|
||||||
// queue is empty
|
|
||||||
```
|
|
||||||
|
|
||||||
### Documentation
|
|
||||||
Documentation can be found at [godoc.org/github.com/foize/go.fifo](http://godoc.org/github.com/foize/go.fifo).
|
|
||||||
For more detailed documentation, read the source.
|
|
||||||
|
|
||||||
### History
|
|
||||||
This package is based on github.com/yasushi-saito/fifo_queue
|
|
||||||
There are several differences:
|
|
||||||
- renamed package to `fifo` to make usage simpler
|
|
||||||
- removed intermediate type `Item` and now directly using interface{} instead.
|
|
||||||
- renamed (*Queue).PushBack() to (*Queue).Add()
|
|
||||||
- renamed (*Queue).PopFront() to (*Queue).Next()
|
|
||||||
- Next() will not panic on empty queue, will just return nil interface{}
|
|
||||||
- Add() does not accept nil interface{} and will panic when trying to add nil interface{}.
|
|
||||||
- Made fifo.Queue thread/goroutine-safe (sync.Mutex)
|
|
||||||
- Added a lot of comments
|
|
||||||
- renamed internal variable/field names
|
|
||||||
-13
@@ -1,13 +0,0 @@
|
|||||||
codecov:
|
|
||||||
# across
|
|
||||||
notify:
|
|
||||||
# Do not notify until at least this number of reports have been uploaded
|
|
||||||
# from the CI pipeline. We normally have more than that number, but 6
|
|
||||||
# should be enough to get a first notification.
|
|
||||||
after_n_builds: 6
|
|
||||||
coverage:
|
|
||||||
status:
|
|
||||||
project:
|
|
||||||
default:
|
|
||||||
# Do not fail the commit status if the coverage was reduced up to this value
|
|
||||||
threshold: 0.5%
|
|
||||||
-40
@@ -1,40 +0,0 @@
|
|||||||
minVersion: 0.35.0
|
|
||||||
changelogPolicy: simple
|
|
||||||
artifactProvider:
|
|
||||||
name: none
|
|
||||||
targets:
|
|
||||||
- name: github
|
|
||||||
tagPrefix: v
|
|
||||||
- name: github
|
|
||||||
tagPrefix: otel/v
|
|
||||||
tagOnly: true
|
|
||||||
- name: github
|
|
||||||
tagPrefix: echo/v
|
|
||||||
tagOnly: true
|
|
||||||
- name: github
|
|
||||||
tagPrefix: fasthttp/v
|
|
||||||
tagOnly: true
|
|
||||||
- name: github
|
|
||||||
tagPrefix: fiber/v
|
|
||||||
tagOnly: true
|
|
||||||
- name: github
|
|
||||||
tagPrefix: gin/v
|
|
||||||
tagOnly: true
|
|
||||||
- name: github
|
|
||||||
tagPrefix: iris/v
|
|
||||||
tagOnly: true
|
|
||||||
- name: github
|
|
||||||
tagPrefix: negroni/v
|
|
||||||
tagOnly: true
|
|
||||||
- name: github
|
|
||||||
tagPrefix: logrus/v
|
|
||||||
tagOnly: true
|
|
||||||
- name: github
|
|
||||||
tagPrefix: slog/v
|
|
||||||
tagOnly: true
|
|
||||||
- name: github
|
|
||||||
tagPrefix: zerolog/v
|
|
||||||
tagOnly: true
|
|
||||||
- name: registry
|
|
||||||
sdks:
|
|
||||||
github:getsentry/sentry-go:
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
# Tell Git to use LF for line endings on all platforms.
|
|
||||||
# Required to have correct test data on Windows.
|
|
||||||
# https://github.com/mvdan/github-actions-golang#caveats
|
|
||||||
# https://github.com/actions/checkout/issues/135#issuecomment-613361104
|
|
||||||
* text eol=lf
|
|
||||||
-14
@@ -1,14 +0,0 @@
|
|||||||
# Code coverage artifacts
|
|
||||||
coverage.txt
|
|
||||||
coverage.out
|
|
||||||
coverage.html
|
|
||||||
.coverage/
|
|
||||||
|
|
||||||
# Just my personal way of tracking stuff — Kamil
|
|
||||||
FIXME.md
|
|
||||||
TODO.md
|
|
||||||
!NOTES.md
|
|
||||||
|
|
||||||
# IDE system files
|
|
||||||
.idea
|
|
||||||
.vscode
|
|
||||||
-46
@@ -1,46 +0,0 @@
|
|||||||
linters:
|
|
||||||
disable-all: true
|
|
||||||
enable:
|
|
||||||
- bodyclose
|
|
||||||
- dogsled
|
|
||||||
- dupl
|
|
||||||
- errcheck
|
|
||||||
- exportloopref
|
|
||||||
- gochecknoinits
|
|
||||||
- goconst
|
|
||||||
- gocritic
|
|
||||||
- gocyclo
|
|
||||||
- godot
|
|
||||||
- gofmt
|
|
||||||
- goimports
|
|
||||||
- gosec
|
|
||||||
- gosimple
|
|
||||||
- govet
|
|
||||||
- ineffassign
|
|
||||||
- misspell
|
|
||||||
- nakedret
|
|
||||||
- prealloc
|
|
||||||
- revive
|
|
||||||
- staticcheck
|
|
||||||
- typecheck
|
|
||||||
- unconvert
|
|
||||||
- unparam
|
|
||||||
- unused
|
|
||||||
- whitespace
|
|
||||||
issues:
|
|
||||||
exclude-rules:
|
|
||||||
- path: _test\.go
|
|
||||||
linters:
|
|
||||||
- goconst
|
|
||||||
- prealloc
|
|
||||||
- path: _test\.go
|
|
||||||
text: "G306:"
|
|
||||||
linters:
|
|
||||||
- gosec
|
|
||||||
- path: errors_test\.go
|
|
||||||
linters:
|
|
||||||
- unused
|
|
||||||
- path: http/example_test\.go
|
|
||||||
linters:
|
|
||||||
- errcheck
|
|
||||||
- bodyclose
|
|
||||||
-960
@@ -1,960 +0,0 @@
|
|||||||
# Changelog
|
|
||||||
|
|
||||||
## 0.31.1
|
|
||||||
|
|
||||||
The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.31.1.
|
|
||||||
|
|
||||||
### Bug Fixes
|
|
||||||
|
|
||||||
- Correct wrong module name for `sentry-go/logrus` ([#950](https://github.com/getsentry/sentry-go/pull/950))
|
|
||||||
|
|
||||||
## 0.31.0
|
|
||||||
|
|
||||||
The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.31.0.
|
|
||||||
|
|
||||||
### Breaking Changes
|
|
||||||
|
|
||||||
- Remove support for metrics. Read more about the end of the Metrics beta [here](https://sentry.zendesk.com/hc/en-us/articles/26369339769883-Metrics-Beta-Ended-on-October-7th). ([#914](https://github.com/getsentry/sentry-go/pull/914))
|
|
||||||
|
|
||||||
- Remove support for profiling. ([#915](https://github.com/getsentry/sentry-go/pull/915))
|
|
||||||
|
|
||||||
- Remove `Segment` field from the `User` struct. This field is no longer used in the Sentry product. ([#928](https://github.com/getsentry/sentry-go/pull/928))
|
|
||||||
|
|
||||||
- Every integration is now a separate module, reducing the binary size and number of dependencies. Once you update `sentry-go` to latest version, you'll need to `go get` the integration you want to use. For example, if you want to use the `echo` integration, you'll need to run `go get github.com/getsentry/sentry-go/echo` ([#919](github.com/getsentry/sentry-go/pull/919)).
|
|
||||||
|
|
||||||
### Features
|
|
||||||
|
|
||||||
Add the ability to override `hub` in `context` for integrations that use custom context. ([#931](https://github.com/getsentry/sentry-go/pull/931))
|
|
||||||
|
|
||||||
- Add `HubProvider` Hook for `sentrylogrus`, enabling dynamic Sentry hub allocation for each log entry or goroutine. ([#936](https://github.com/getsentry/sentry-go/pull/936))
|
|
||||||
|
|
||||||
This change enhances compatibility with Sentry's recommendation of using separate hubs per goroutine. To ensure a separate Sentry hub for each goroutine, configure the `HubProvider` like this:
|
|
||||||
|
|
||||||
```go
|
|
||||||
hook, err := sentrylogrus.New(nil, sentry.ClientOptions{})
|
|
||||||
if err != nil {
|
|
||||||
log.Fatalf("Failed to initialize Sentry hook: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Set a custom HubProvider to generate a new hub for each goroutine or log entry
|
|
||||||
hook.SetHubProvider(func() *sentry.Hub {
|
|
||||||
client, _ := sentry.NewClient(sentry.ClientOptions{})
|
|
||||||
return sentry.NewHub(client, sentry.NewScope())
|
|
||||||
})
|
|
||||||
|
|
||||||
logrus.AddHook(hook)
|
|
||||||
```
|
|
||||||
|
|
||||||
### Bug Fixes
|
|
||||||
|
|
||||||
- Add support for closing worker goroutines started by the `HTTPTranport` to prevent goroutine leaks. ([#894](https://github.com/getsentry/sentry-go/pull/894))
|
|
||||||
|
|
||||||
```go
|
|
||||||
client, _ := sentry.NewClient()
|
|
||||||
defer client.Close()
|
|
||||||
```
|
|
||||||
|
|
||||||
Worker can be also closed by calling `Close()` method on the `HTTPTransport` instance. `Close` should be called after `Flush` and before terminating the program otherwise some events may be lost.
|
|
||||||
|
|
||||||
```go
|
|
||||||
transport := sentry.NewHTTPTransport()
|
|
||||||
defer transport.Close()
|
|
||||||
```
|
|
||||||
|
|
||||||
### Misc
|
|
||||||
|
|
||||||
- Bump [gin-gonic/gin](https://github.com/gin-gonic/gin) to v1.9.1. ([#946](https://github.com/getsentry/sentry-go/pull/946))
|
|
||||||
|
|
||||||
## 0.30.0
|
|
||||||
|
|
||||||
The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.30.0.
|
|
||||||
|
|
||||||
### Features
|
|
||||||
|
|
||||||
- Add `sentryzerolog` integration ([#857](https://github.com/getsentry/sentry-go/pull/857))
|
|
||||||
- Add `sentryslog` integration ([#865](https://github.com/getsentry/sentry-go/pull/865))
|
|
||||||
- Always set Mechanism Type to generic ([#896](https://github.com/getsentry/sentry-go/pull/897))
|
|
||||||
|
|
||||||
### Bug Fixes
|
|
||||||
|
|
||||||
- Prevent panic in `fasthttp` and `fiber` integration in case a malformed URL has to be parsed ([#912](https://github.com/getsentry/sentry-go/pull/912))
|
|
||||||
|
|
||||||
### Misc
|
|
||||||
|
|
||||||
Drop support for Go 1.18, 1.19 and 1.20. The currently supported Go versions are the last 3 stable releases: 1.23, 1.22 and 1.21.
|
|
||||||
|
|
||||||
## 0.29.1
|
|
||||||
|
|
||||||
The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.29.1.
|
|
||||||
|
|
||||||
### Bug Fixes
|
|
||||||
|
|
||||||
- Correlate errors to the current trace ([#886](https://github.com/getsentry/sentry-go/pull/886))
|
|
||||||
- Set the trace context when the transaction finishes ([#888](https://github.com/getsentry/sentry-go/pull/888))
|
|
||||||
|
|
||||||
### Misc
|
|
||||||
|
|
||||||
- Update the `sentrynegroni` integration to use the latest (v3.1.1) version of Negroni ([#885](https://github.com/getsentry/sentry-go/pull/885))
|
|
||||||
|
|
||||||
## 0.29.0
|
|
||||||
|
|
||||||
The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.29.0.
|
|
||||||
|
|
||||||
### Breaking Changes
|
|
||||||
|
|
||||||
- Remove the `sentrymartini` integration ([#861](https://github.com/getsentry/sentry-go/pull/861))
|
|
||||||
- The `WrapResponseWriter` has been moved from the `sentryhttp` package to the `internal/httputils` package. If you've imported it previosuly, you'll need to copy the implementation in your project. ([#871](https://github.com/getsentry/sentry-go/pull/871))
|
|
||||||
|
|
||||||
### Features
|
|
||||||
|
|
||||||
- Add new convenience methods to continue a trace and propagate tracing headers for error-only use cases. ([#862](https://github.com/getsentry/sentry-go/pull/862))
|
|
||||||
|
|
||||||
If you are not using one of our integrations, you can manually continue an incoming trace by using `sentry.ContinueTrace()` by providing the `sentry-trace` and `baggage` header received from a downstream SDK.
|
|
||||||
|
|
||||||
```go
|
|
||||||
hub := sentry.CurrentHub()
|
|
||||||
sentry.ContinueTrace(hub, r.Header.Get(sentry.SentryTraceHeader), r.Header.Get(sentry.SentryBaggageHeader)),
|
|
||||||
```
|
|
||||||
|
|
||||||
You can use `hub.GetTraceparent()` and `hub.GetBaggage()` to fetch the necessary header values for outgoing HTTP requests.
|
|
||||||
|
|
||||||
```go
|
|
||||||
hub := sentry.GetHubFromContext(ctx)
|
|
||||||
req, _ := http.NewRequest("GET", "http://localhost:3000", nil)
|
|
||||||
req.Header.Add(sentry.SentryTraceHeader, hub.GetTraceparent())
|
|
||||||
req.Header.Add(sentry.SentryBaggageHeader, hub.GetBaggage())
|
|
||||||
```
|
|
||||||
|
|
||||||
### Bug Fixes
|
|
||||||
|
|
||||||
- Initialize `HTTPTransport.limit` if `nil` ([#844](https://github.com/getsentry/sentry-go/pull/844))
|
|
||||||
- Fix `sentry.StartTransaction()` returning a transaction with an outdated context on existing transactions ([#854](https://github.com/getsentry/sentry-go/pull/854))
|
|
||||||
- Treat `Proxy-Authorization` as a sensitive header ([#859](https://github.com/getsentry/sentry-go/pull/859))
|
|
||||||
- Add support for the `http.Hijacker` interface to the `sentrynegroni` package ([#871](https://github.com/getsentry/sentry-go/pull/871))
|
|
||||||
- Go version >= 1.23: Use value from `http.Request.Pattern` for HTTP transaction names when using `sentryhttp` & `sentrynegroni` ([#875](https://github.com/getsentry/sentry-go/pull/875))
|
|
||||||
- Go version >= 1.21: Fix closure functions name grouping ([#877](https://github.com/getsentry/sentry-go/pull/877))
|
|
||||||
|
|
||||||
### Misc
|
|
||||||
|
|
||||||
- Collect `span` origins ([#849](https://github.com/getsentry/sentry-go/pull/849))
|
|
||||||
|
|
||||||
## 0.28.1
|
|
||||||
|
|
||||||
The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.28.1.
|
|
||||||
|
|
||||||
### Bug Fixes
|
|
||||||
|
|
||||||
- Implement `http.ResponseWriter` to hook into various parts of the response process ([#837](https://github.com/getsentry/sentry-go/pull/837))
|
|
||||||
|
|
||||||
## 0.28.0
|
|
||||||
|
|
||||||
The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.28.0.
|
|
||||||
|
|
||||||
### Features
|
|
||||||
|
|
||||||
- Add a `Fiber` performance tracing & error reporting integration ([#795](https://github.com/getsentry/sentry-go/pull/795))
|
|
||||||
- Add performance tracing to the `Echo` integration ([#722](https://github.com/getsentry/sentry-go/pull/722))
|
|
||||||
- Add performance tracing to the `FastHTTP` integration ([#732](https://github.com/getsentry/sentry-go/pull/723))
|
|
||||||
- Add performance tracing to the `Iris` integration ([#809](https://github.com/getsentry/sentry-go/pull/809))
|
|
||||||
- Add performance tracing to the `Negroni` integration ([#808](https://github.com/getsentry/sentry-go/pull/808))
|
|
||||||
- Add `FailureIssueThreshold` & `RecoveryThreshold` to `MonitorConfig` ([#775](https://github.com/getsentry/sentry-go/pull/775))
|
|
||||||
- Use `errors.Unwrap()` to create exception groups ([#792](https://github.com/getsentry/sentry-go/pull/792))
|
|
||||||
- Add support for matching on strings for `ClientOptions.IgnoreErrors` & `ClientOptions.IgnoreTransactions` ([#819](https://github.com/getsentry/sentry-go/pull/819))
|
|
||||||
- Add `http.request.method` attribute for performance span data ([#786](https://github.com/getsentry/sentry-go/pull/786))
|
|
||||||
- Accept `interface{}` for span data values ([#784](https://github.com/getsentry/sentry-go/pull/784))
|
|
||||||
|
|
||||||
### Bug Fixes
|
|
||||||
|
|
||||||
- Fix missing stack trace for parsing error in `logrusentry` ([#689](https://github.com/getsentry/sentry-go/pull/689))
|
|
||||||
|
|
||||||
## 0.27.0
|
|
||||||
|
|
||||||
The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.27.0.
|
|
||||||
|
|
||||||
### Breaking Changes
|
|
||||||
|
|
||||||
- `Exception.ThreadId` is now typed as `uint64`. It was wrongly typed as `string` before. ([#770](https://github.com/getsentry/sentry-go/pull/770))
|
|
||||||
|
|
||||||
### Misc
|
|
||||||
|
|
||||||
- Export `Event.Attachments` ([#771](https://github.com/getsentry/sentry-go/pull/771))
|
|
||||||
|
|
||||||
## 0.26.0
|
|
||||||
|
|
||||||
The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.26.0.
|
|
||||||
|
|
||||||
### Breaking Changes
|
|
||||||
|
|
||||||
As previously announced, this release removes some methods from the SDK.
|
|
||||||
|
|
||||||
- `sentry.TransactionName()` use `sentry.WithTransactionName()` instead.
|
|
||||||
- `sentry.OpName()` use `sentry.WithOpName()` instead.
|
|
||||||
- `sentry.TransctionSource()` use `sentry.WithTransactionSource()` instead.
|
|
||||||
- `sentry.SpanSampled()` use `sentry.WithSpanSampled()` instead.
|
|
||||||
|
|
||||||
### Features
|
|
||||||
|
|
||||||
- Add `WithDescription` span option ([#751](https://github.com/getsentry/sentry-go/pull/751))
|
|
||||||
|
|
||||||
```go
|
|
||||||
span := sentry.StartSpan(ctx, "http.client", WithDescription("GET /api/users"))
|
|
||||||
```
|
|
||||||
- Add support for package name parsing in Go 1.20 and higher ([#730](https://github.com/getsentry/sentry-go/pull/730))
|
|
||||||
|
|
||||||
### Bug Fixes
|
|
||||||
|
|
||||||
- Apply `ClientOptions.SampleRate` only to errors & messages ([#754](https://github.com/getsentry/sentry-go/pull/754))
|
|
||||||
- Check if git is available before executing any git commands ([#737](https://github.com/getsentry/sentry-go/pull/737))
|
|
||||||
|
|
||||||
## 0.25.0
|
|
||||||
|
|
||||||
The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.25.0.
|
|
||||||
|
|
||||||
### Breaking Changes
|
|
||||||
|
|
||||||
As previously announced, this release removes two global constants from the SDK.
|
|
||||||
|
|
||||||
- `sentry.Version` was removed. Use `sentry.SDKVersion` instead ([#727](https://github.com/getsentry/sentry-go/pull/727))
|
|
||||||
- `sentry.SDKIdentifier` was removed. Use `Client.GetSDKIdentifier()` instead ([#727](https://github.com/getsentry/sentry-go/pull/727))
|
|
||||||
|
|
||||||
### Features
|
|
||||||
|
|
||||||
- Add `ClientOptions.IgnoreTransactions`, which allows you to ignore specific transactions based on their name ([#717](https://github.com/getsentry/sentry-go/pull/717))
|
|
||||||
- Add `ClientOptions.Tags`, which allows you to set global tags that are applied to all events. You can also define tags by setting `SENTRY_TAGS_` environment variables ([#718](https://github.com/getsentry/sentry-go/pull/718))
|
|
||||||
|
|
||||||
### Bug fixes
|
|
||||||
|
|
||||||
- Fix an issue in the profiler that would cause an infinite loop if the duration of a transaction is longer than 30 seconds ([#724](https://github.com/getsentry/sentry-go/issues/724))
|
|
||||||
|
|
||||||
### Misc
|
|
||||||
|
|
||||||
- `dsn.RequestHeaders()` is not to be removed, though it is still considered deprecated and should only be used when using a custom transport that sends events to the `/store` endpoint ([#720](https://github.com/getsentry/sentry-go/pull/720))
|
|
||||||
|
|
||||||
## 0.24.1
|
|
||||||
|
|
||||||
The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.24.1.
|
|
||||||
|
|
||||||
### Bug fixes
|
|
||||||
|
|
||||||
- Prevent a panic in `sentryotel.flushSpanProcessor()` ([(#711)](https://github.com/getsentry/sentry-go/pull/711))
|
|
||||||
- Prevent a panic when setting the SDK identifier ([#715](https://github.com/getsentry/sentry-go/pull/715))
|
|
||||||
|
|
||||||
## 0.24.0
|
|
||||||
|
|
||||||
The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.24.0.
|
|
||||||
|
|
||||||
### Deprecations
|
|
||||||
|
|
||||||
- `sentry.Version` to be removed in 0.25.0. Use `sentry.SDKVersion` instead.
|
|
||||||
- `sentry.SDKIdentifier` to be removed in 0.25.0. Use `Client.GetSDKIdentifier()` instead.
|
|
||||||
- `dsn.RequestHeaders()` to be removed after 0.25.0, but no earlier than December 1, 2023. Requests to the `/envelope` endpoint are authenticated using the DSN in the envelope header.
|
|
||||||
|
|
||||||
### Features
|
|
||||||
|
|
||||||
- Run a single instance of the profiler instead of multiple ones for each Go routine ([#655](https://github.com/getsentry/sentry-go/pull/655))
|
|
||||||
- Use the route path as the transaction names when using the Gin integration ([#675](https://github.com/getsentry/sentry-go/pull/675))
|
|
||||||
- Set the SDK name accordingly when a framework integration is used ([#694](https://github.com/getsentry/sentry-go/pull/694))
|
|
||||||
- Read release information (VCS revision) from `debug.ReadBuildInfo` ([#704](https://github.com/getsentry/sentry-go/pull/704))
|
|
||||||
|
|
||||||
### Bug fixes
|
|
||||||
|
|
||||||
- [otel] Fix incorrect usage of `attributes.Value.AsString` ([#684](https://github.com/getsentry/sentry-go/pull/684))
|
|
||||||
- Fix trace function name parsing in profiler on go1.21+ ([#695](https://github.com/getsentry/sentry-go/pull/695))
|
|
||||||
|
|
||||||
### Misc
|
|
||||||
|
|
||||||
- Test against Go 1.21 ([#695](https://github.com/getsentry/sentry-go/pull/695))
|
|
||||||
- Make tests more robust ([#698](https://github.com/getsentry/sentry-go/pull/698), [#699](https://github.com/getsentry/sentry-go/pull/699), [#700](https://github.com/getsentry/sentry-go/pull/700), [#702](https://github.com/getsentry/sentry-go/pull/702))
|
|
||||||
|
|
||||||
## 0.23.0
|
|
||||||
|
|
||||||
The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.23.0.
|
|
||||||
|
|
||||||
### Features
|
|
||||||
|
|
||||||
- Initial support for [Cron Monitoring](https://docs.sentry.io/product/crons/) ([#661](https://github.com/getsentry/sentry-go/pull/661))
|
|
||||||
|
|
||||||
This is how the basic usage of the feature looks like:
|
|
||||||
|
|
||||||
```go
|
|
||||||
// 🟡 Notify Sentry your job is running:
|
|
||||||
checkinId := sentry.CaptureCheckIn(
|
|
||||||
&sentry.CheckIn{
|
|
||||||
MonitorSlug: "<monitor-slug>",
|
|
||||||
Status: sentry.CheckInStatusInProgress,
|
|
||||||
},
|
|
||||||
nil,
|
|
||||||
)
|
|
||||||
|
|
||||||
// Execute your scheduled task here...
|
|
||||||
|
|
||||||
// 🟢 Notify Sentry your job has completed successfully:
|
|
||||||
sentry.CaptureCheckIn(
|
|
||||||
&sentry.CheckIn{
|
|
||||||
ID: *checkinId,
|
|
||||||
MonitorSlug: "<monitor-slug>",
|
|
||||||
Status: sentry.CheckInStatusOK,
|
|
||||||
},
|
|
||||||
nil,
|
|
||||||
)
|
|
||||||
```
|
|
||||||
|
|
||||||
A full example of using Crons Monitoring is available [here](https://github.com/getsentry/sentry-go/blob/dde4d360660838f3c2e0ced8205bc8f7a8d312d9/_examples/crons/main.go).
|
|
||||||
|
|
||||||
More documentation on configuring and using Crons [can be found here](https://docs.sentry.io/platforms/go/crons/).
|
|
||||||
|
|
||||||
- Add support for [Event Attachments](https://docs.sentry.io/platforms/go/enriching-events/attachments/) ([#670](https://github.com/getsentry/sentry-go/pull/670))
|
|
||||||
|
|
||||||
It's now possible to add file/binary payloads to Sentry events:
|
|
||||||
|
|
||||||
```go
|
|
||||||
sentry.ConfigureScope(func(scope *sentry.Scope) {
|
|
||||||
scope.AddAttachment(&Attachment{
|
|
||||||
Filename: "report.html",
|
|
||||||
ContentType: "text/html",
|
|
||||||
Payload: []byte("<h1>Look, HTML</h1>"),
|
|
||||||
})
|
|
||||||
})
|
|
||||||
```
|
|
||||||
|
|
||||||
The attachment will then be accessible on the Issue Details page.
|
|
||||||
|
|
||||||
- Add sampling decision to trace envelope header ([#666](https://github.com/getsentry/sentry-go/pull/666))
|
|
||||||
- Expose SpanFromContext function ([#672](https://github.com/getsentry/sentry-go/pull/672))
|
|
||||||
|
|
||||||
### Bug fixes
|
|
||||||
|
|
||||||
- Make `Span.Finish` a no-op when the span is already finished ([#660](https://github.com/getsentry/sentry-go/pull/660))
|
|
||||||
|
|
||||||
## 0.22.0
|
|
||||||
|
|
||||||
The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.22.0.
|
|
||||||
|
|
||||||
This release contains initial [profiling](https://docs.sentry.io/product/profiling/) support, as well as a few bug fixes and improvements.
|
|
||||||
|
|
||||||
### Features
|
|
||||||
|
|
||||||
- Initial (alpha) support for [profiling](https://docs.sentry.io/product/profiling/) ([#626](https://github.com/getsentry/sentry-go/pull/626))
|
|
||||||
|
|
||||||
Profiling is disabled by default. To enable it, configure both `TracesSampleRate` and `ProfilesSampleRate` when initializing the SDK:
|
|
||||||
|
|
||||||
```go
|
|
||||||
err := sentry.Init(sentry.ClientOptions{
|
|
||||||
Dsn: "__DSN__",
|
|
||||||
EnableTracing: true,
|
|
||||||
TracesSampleRate: 1.0,
|
|
||||||
// The sampling rate for profiling is relative to TracesSampleRate. In this case, we'll capture profiles for 100% of transactions.
|
|
||||||
ProfilesSampleRate: 1.0,
|
|
||||||
})
|
|
||||||
```
|
|
||||||
|
|
||||||
More documentation on profiling and current limitations [can be found here](https://docs.sentry.io/platforms/go/profiling/).
|
|
||||||
|
|
||||||
- Add transactions/tracing support go the Gin integration ([#644](https://github.com/getsentry/sentry-go/pull/644))
|
|
||||||
|
|
||||||
### Bug fixes
|
|
||||||
|
|
||||||
- Always set a valid source on transactions ([#637](https://github.com/getsentry/sentry-go/pull/637))
|
|
||||||
- Clone scope.Context in more places to avoid panics on concurrent reads and writes ([#638](https://github.com/getsentry/sentry-go/pull/638))
|
|
||||||
- Fixes [#570](https://github.com/getsentry/sentry-go/issues/570)
|
|
||||||
- Fix frames recognized as not being in-app still showing as in-app ([#647](https://github.com/getsentry/sentry-go/pull/647))
|
|
||||||
|
|
||||||
## 0.21.0
|
|
||||||
|
|
||||||
The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.21.0.
|
|
||||||
|
|
||||||
Note: this release includes one **breaking change** and some **deprecations**, which are listed below.
|
|
||||||
|
|
||||||
### Breaking Changes
|
|
||||||
|
|
||||||
**This change does not apply if you use [https://sentry.io](https://sentry.io)**
|
|
||||||
|
|
||||||
- Remove support for the `/store` endpoint ([#631](https://github.com/getsentry/sentry-go/pull/631))
|
|
||||||
- This change requires a self-hosted version of Sentry 20.6.0 or higher. If you are using a version of [self-hosted Sentry](https://develop.sentry.dev/self-hosted/) (aka *on-premise*) older than 20.6.0, then you will need to [upgrade](https://develop.sentry.dev/self-hosted/releases/) your instance.
|
|
||||||
|
|
||||||
### Features
|
|
||||||
|
|
||||||
- Rename four span option functions ([#611](https://github.com/getsentry/sentry-go/pull/611), [#624](https://github.com/getsentry/sentry-go/pull/624))
|
|
||||||
- `TransctionSource` -> `WithTransactionSource`
|
|
||||||
- `SpanSampled` -> `WithSpanSampled`
|
|
||||||
- `OpName` -> `WithOpName`
|
|
||||||
- `TransactionName` -> `WithTransactionName`
|
|
||||||
- Old functions `TransctionSource`, `SpanSampled`, `OpName`, and `TransactionName` are still available but are now **deprecated** and will be removed in a future release.
|
|
||||||
- Make `client.EventFromMessage` and `client.EventFromException` methods public ([#607](https://github.com/getsentry/sentry-go/pull/607))
|
|
||||||
- Add `client.SetException` method ([#607](https://github.com/getsentry/sentry-go/pull/607))
|
|
||||||
- This allows to set or add errors to an existing `Event`.
|
|
||||||
|
|
||||||
### Bug Fixes
|
|
||||||
|
|
||||||
- Protect from panics while doing concurrent reads/writes to Span data fields ([#609](https://github.com/getsentry/sentry-go/pull/609))
|
|
||||||
- [otel] Improve detection of Sentry-related spans ([#632](https://github.com/getsentry/sentry-go/pull/632), [#636](https://github.com/getsentry/sentry-go/pull/636))
|
|
||||||
- Fixes cases when HTTP spans containing requests to Sentry were captured by Sentry ([#627](https://github.com/getsentry/sentry-go/issues/627))
|
|
||||||
|
|
||||||
### Misc
|
|
||||||
|
|
||||||
- Drop testing in (legacy) GOPATH mode ([#618](https://github.com/getsentry/sentry-go/pull/618))
|
|
||||||
- Remove outdated documentation from https://pkg.go.dev/github.com/getsentry/sentry-go ([#623](https://github.com/getsentry/sentry-go/pull/623))
|
|
||||||
|
|
||||||
## 0.20.0
|
|
||||||
|
|
||||||
The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.20.0.
|
|
||||||
|
|
||||||
Note: this release has some **breaking changes**, which are listed below.
|
|
||||||
|
|
||||||
### Breaking Changes
|
|
||||||
|
|
||||||
- Remove the following methods: `Scope.SetTransaction()`, `Scope.Transaction()` ([#605](https://github.com/getsentry/sentry-go/pull/605))
|
|
||||||
|
|
||||||
Span.Name should be used instead to access the transaction's name.
|
|
||||||
|
|
||||||
For example, the following [`TracesSampler`](https://docs.sentry.io/platforms/go/configuration/sampling/#setting-a-sampling-function) function should be now written as follows:
|
|
||||||
|
|
||||||
**Before:**
|
|
||||||
```go
|
|
||||||
TracesSampler: func(ctx sentry.SamplingContext) float64 {
|
|
||||||
hub := sentry.GetHubFromContext(ctx.Span.Context())
|
|
||||||
if hub.Scope().Transaction() == "GET /health" {
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
return 1
|
|
||||||
},
|
|
||||||
```
|
|
||||||
|
|
||||||
**After:**
|
|
||||||
```go
|
|
||||||
TracesSampler: func(ctx sentry.SamplingContext) float64 {
|
|
||||||
if ctx.Span.Name == "GET /health" {
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
return 1
|
|
||||||
},
|
|
||||||
```
|
|
||||||
|
|
||||||
### Features
|
|
||||||
|
|
||||||
- Add `Span.SetContext()` method ([#599](https://github.com/getsentry/sentry-go/pull/599/))
|
|
||||||
- It is recommended to use it instead of `hub.Scope().SetContext` when setting or updating context on transactions.
|
|
||||||
- Add `DebugMeta` interface to `Event` and extend `Frame` structure with more fields ([#606](https://github.com/getsentry/sentry-go/pull/606))
|
|
||||||
- More about DebugMeta interface [here](https://develop.sentry.dev/sdk/event-payloads/debugmeta/).
|
|
||||||
|
|
||||||
### Bug Fixes
|
|
||||||
|
|
||||||
- [otel] Fix missing OpenTelemetry context on some events ([#599](https://github.com/getsentry/sentry-go/pull/599), [#605](https://github.com/getsentry/sentry-go/pull/605))
|
|
||||||
- Fixes ([#596](https://github.com/getsentry/sentry-go/issues/596)).
|
|
||||||
- [otel] Better handling for HTTP span attributes ([#610](https://github.com/getsentry/sentry-go/pull/610))
|
|
||||||
|
|
||||||
### Misc
|
|
||||||
|
|
||||||
- Bump minimum versions: `github.com/kataras/iris/v12` to 12.2.0, `github.com/labstack/echo/v4` to v4.10.0 ([#595](https://github.com/getsentry/sentry-go/pull/595))
|
|
||||||
- Resolves [GO-2022-1144 / CVE-2022-41717](https://deps.dev/advisory/osv/GO-2022-1144), [GO-2023-1495 / CVE-2022-41721](https://deps.dev/advisory/osv/GO-2023-1495), [GO-2022-1059 / CVE-2022-32149](https://deps.dev/advisory/osv/GO-2022-1059).
|
|
||||||
- Bump `google.golang.org/protobuf` minimum required version to 1.29.1 ([#604](https://github.com/getsentry/sentry-go/pull/604))
|
|
||||||
- This fixes a potential denial of service issue ([CVE-2023-24535](https://github.com/advisories/GHSA-hw7c-3rfg-p46j)).
|
|
||||||
- Exclude the `otel` module when building in GOPATH mode ([#615](https://github.com/getsentry/sentry-go/pull/615))
|
|
||||||
|
|
||||||
## 0.19.0
|
|
||||||
|
|
||||||
The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.19.0.
|
|
||||||
|
|
||||||
### Features
|
|
||||||
|
|
||||||
- Add support for exception mechanism metadata ([#564](https://github.com/getsentry/sentry-go/pull/564/))
|
|
||||||
- More about exception mechanisms [here](https://develop.sentry.dev/sdk/event-payloads/exception/#exception-mechanism).
|
|
||||||
|
|
||||||
### Bug Fixes
|
|
||||||
- [otel] Use the correct "trace" context when sending a Sentry error ([#580](https://github.com/getsentry/sentry-go/pull/580/))
|
|
||||||
|
|
||||||
|
|
||||||
### Misc
|
|
||||||
- Drop support for Go 1.17, add support for Go 1.20 ([#563](https://github.com/getsentry/sentry-go/pull/563/))
|
|
||||||
- According to our policy, we're officially supporting the last three minor releases of Go.
|
|
||||||
- Switch repository license to MIT ([#583](https://github.com/getsentry/sentry-go/pull/583/))
|
|
||||||
- More about Sentry licensing [here](https://open.sentry.io/licensing/).
|
|
||||||
- Bump `golang.org/x/text` minimum required version to 0.3.8 ([#586](https://github.com/getsentry/sentry-go/pull/586))
|
|
||||||
- This fixes [CVE-2022-32149](https://github.com/advisories/GHSA-69ch-w2m2-3vjp) vulnerability.
|
|
||||||
|
|
||||||
## 0.18.0
|
|
||||||
|
|
||||||
The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.18.0.
|
|
||||||
This release contains initial support for [OpenTelemetry](https://opentelemetry.io/) and various other bug fixes and improvements.
|
|
||||||
|
|
||||||
**Note**: This is the last release supporting Go 1.17.
|
|
||||||
|
|
||||||
### Features
|
|
||||||
|
|
||||||
- Initial support for [OpenTelemetry](https://opentelemetry.io/).
|
|
||||||
You can now send all your OpenTelemetry spans to Sentry.
|
|
||||||
|
|
||||||
Install the `otel` module
|
|
||||||
|
|
||||||
```bash
|
|
||||||
go get github.com/getsentry/sentry-go \
|
|
||||||
github.com/getsentry/sentry-go/otel
|
|
||||||
```
|
|
||||||
|
|
||||||
Configure the Sentry and OpenTelemetry SDKs
|
|
||||||
|
|
||||||
```go
|
|
||||||
import (
|
|
||||||
"go.opentelemetry.io/otel"
|
|
||||||
sdktrace "go.opentelemetry.io/otel/sdk/trace"
|
|
||||||
"github.com/getsentry/sentry-go"
|
|
||||||
"github.com/getsentry/sentry-go/otel"
|
|
||||||
// ...
|
|
||||||
)
|
|
||||||
|
|
||||||
// Initlaize the Sentry SDK
|
|
||||||
sentry.Init(sentry.ClientOptions{
|
|
||||||
Dsn: "__DSN__",
|
|
||||||
EnableTracing: true,
|
|
||||||
TracesSampleRate: 1.0,
|
|
||||||
})
|
|
||||||
|
|
||||||
// Set up the Sentry span processor
|
|
||||||
tp := sdktrace.NewTracerProvider(
|
|
||||||
sdktrace.WithSpanProcessor(sentryotel.NewSentrySpanProcessor()),
|
|
||||||
// ...
|
|
||||||
)
|
|
||||||
otel.SetTracerProvider(tp)
|
|
||||||
|
|
||||||
// Set up the Sentry propagator
|
|
||||||
otel.SetTextMapPropagator(sentryotel.NewSentryPropagator())
|
|
||||||
```
|
|
||||||
|
|
||||||
You can read more about using OpenTelemetry with Sentry in our [docs](https://docs.sentry.io/platforms/go/performance/instrumentation/opentelemetry/).
|
|
||||||
|
|
||||||
### Bug Fixes
|
|
||||||
|
|
||||||
- Do not freeze the Dynamic Sampling Context when no Sentry values are present in the baggage header ([#532](https://github.com/getsentry/sentry-go/pull/532))
|
|
||||||
- Create a frozen Dynamic Sampling Context when calling `span.ToBaggage()` ([#566](https://github.com/getsentry/sentry-go/pull/566))
|
|
||||||
- Fix baggage parsing and encoding in vendored otel package ([#568](https://github.com/getsentry/sentry-go/pull/568))
|
|
||||||
|
|
||||||
### Misc
|
|
||||||
|
|
||||||
- Add `Span.SetDynamicSamplingContext()` ([#539](https://github.com/getsentry/sentry-go/pull/539/))
|
|
||||||
- Add various getters for `Dsn` ([#540](https://github.com/getsentry/sentry-go/pull/540))
|
|
||||||
- Add `SpanOption::SpanSampled` ([#546](https://github.com/getsentry/sentry-go/pull/546))
|
|
||||||
- Add `Span.SetData()` ([#542](https://github.com/getsentry/sentry-go/pull/542))
|
|
||||||
- Add `Span.IsTransaction()` ([#543](https://github.com/getsentry/sentry-go/pull/543))
|
|
||||||
- Add `Span.GetTransaction()` method ([#558](https://github.com/getsentry/sentry-go/pull/558))
|
|
||||||
|
|
||||||
## 0.17.0
|
|
||||||
|
|
||||||
The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.17.0.
|
|
||||||
This release contains a new `BeforeSendTransaction` hook option and corrects two regressions introduced in `0.16.0`.
|
|
||||||
|
|
||||||
### Features
|
|
||||||
|
|
||||||
- Add `BeforeSendTransaction` hook to `ClientOptions` ([#517](https://github.com/getsentry/sentry-go/pull/517))
|
|
||||||
- Here's [an example](https://github.com/getsentry/sentry-go/blob/master/_examples/http/main.go#L56-L66) of how BeforeSendTransaction can be used to modify or drop transaction events.
|
|
||||||
|
|
||||||
### Bug Fixes
|
|
||||||
|
|
||||||
- Do not crash in Span.Finish() when the Client is empty [#520](https://github.com/getsentry/sentry-go/pull/520)
|
|
||||||
- Fixes [#518](https://github.com/getsentry/sentry-go/issues/518)
|
|
||||||
- Attach non-PII/non-sensitive request headers to events when `ClientOptions.SendDefaultPii` is set to `false` ([#524](https://github.com/getsentry/sentry-go/pull/524))
|
|
||||||
- Fixes [#523](https://github.com/getsentry/sentry-go/issues/523)
|
|
||||||
|
|
||||||
### Misc
|
|
||||||
|
|
||||||
- Clarify how to handle logrus.Fatalf events ([#501](https://github.com/getsentry/sentry-go/pull/501/))
|
|
||||||
- Rename the `examples` directory to `_examples` ([#521](https://github.com/getsentry/sentry-go/pull/521))
|
|
||||||
- This removes an indirect dependency to `github.com/golang-jwt/jwt`
|
|
||||||
|
|
||||||
## 0.16.0
|
|
||||||
|
|
||||||
The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.16.0.
|
|
||||||
Due to ongoing work towards a stable API for `v1.0.0`, we sadly had to include **two breaking changes** in this release.
|
|
||||||
|
|
||||||
### Breaking Changes
|
|
||||||
|
|
||||||
- Add `EnableTracing`, a boolean option flag to enable performance monitoring (`false` by default).
|
|
||||||
- If you're using `TracesSampleRate` or `TracesSampler`, this option is **required** to enable performance monitoring.
|
|
||||||
|
|
||||||
```go
|
|
||||||
sentry.Init(sentry.ClientOptions{
|
|
||||||
EnableTracing: true,
|
|
||||||
TracesSampleRate: 1.0,
|
|
||||||
})
|
|
||||||
```
|
|
||||||
- Unify TracesSampler [#498](https://github.com/getsentry/sentry-go/pull/498)
|
|
||||||
- `TracesSampler` was changed to a callback that must return a `float64` between `0.0` and `1.0`.
|
|
||||||
|
|
||||||
For example, you can apply a sample rate of `1.0` (100%) to all `/api` transactions, and a sample rate of `0.5` (50%) to all other transactions.
|
|
||||||
You can read more about this in our [SDK docs](https://docs.sentry.io/platforms/go/configuration/filtering/#using-sampling-to-filter-transaction-events).
|
|
||||||
|
|
||||||
```go
|
|
||||||
sentry.Init(sentry.ClientOptions{
|
|
||||||
TracesSampler: sentry.TracesSampler(func(ctx sentry.SamplingContext) float64 {
|
|
||||||
hub := sentry.GetHubFromContext(ctx.Span.Context())
|
|
||||||
name := hub.Scope().Transaction()
|
|
||||||
|
|
||||||
if strings.HasPrefix(name, "GET /api") {
|
|
||||||
return 1.0
|
|
||||||
}
|
|
||||||
|
|
||||||
return 0.5
|
|
||||||
}),
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### Features
|
|
||||||
|
|
||||||
- Send errors logged with [Logrus](https://github.com/sirupsen/logrus) to Sentry.
|
|
||||||
- Have a look at our [logrus examples](https://github.com/getsentry/sentry-go/blob/master/_examples/logrus/main.go) on how to use the integration.
|
|
||||||
- Add support for Dynamic Sampling [#491](https://github.com/getsentry/sentry-go/pull/491)
|
|
||||||
- You can read more about Dynamic Sampling in our [product docs](https://docs.sentry.io/product/data-management-settings/dynamic-sampling/).
|
|
||||||
- Add detailed logging about the reason transactions are being dropped.
|
|
||||||
- You can enable SDK logging via `sentry.ClientOptions.Debug: true`.
|
|
||||||
|
|
||||||
### Bug Fixes
|
|
||||||
|
|
||||||
- Do not clone the hub when calling `StartTransaction` [#505](https://github.com/getsentry/sentry-go/pull/505)
|
|
||||||
- Fixes [#502](https://github.com/getsentry/sentry-go/issues/502)
|
|
||||||
|
|
||||||
## 0.15.0
|
|
||||||
|
|
||||||
- fix: Scope values should not override Event values (#446)
|
|
||||||
- feat: Make maximum amount of spans configurable (#460)
|
|
||||||
- feat: Add a method to start a transaction (#482)
|
|
||||||
- feat: Extend User interface by adding Data, Name and Segment (#483)
|
|
||||||
- feat: Add ClientOptions.SendDefaultPII (#485)
|
|
||||||
|
|
||||||
## 0.14.0
|
|
||||||
|
|
||||||
- feat: Add function to continue from trace string (#434)
|
|
||||||
- feat: Add `max-depth` options (#428)
|
|
||||||
- *[breaking]* ref: Use a `Context` type mapping to a `map[string]interface{}` for all event contexts (#444)
|
|
||||||
- *[breaking]* ref: Replace deprecated `ioutil` pkg with `os` & `io` (#454)
|
|
||||||
- ref: Optimize `stacktrace.go` from size and speed (#467)
|
|
||||||
- ci: Test against `go1.19` and `go1.18`, drop `go1.16` and `go1.15` support (#432, #477)
|
|
||||||
- deps: Dependency update to fix CVEs (#462, #464, #477)
|
|
||||||
|
|
||||||
_NOTE:_ This version drops support for Go 1.16 and Go 1.15. The currently supported Go versions are the last 3 stable releases: 1.19, 1.18 and 1.17.
|
|
||||||
|
|
||||||
## v0.13.0
|
|
||||||
|
|
||||||
- ref: Change DSN ProjectID to be a string (#420)
|
|
||||||
- fix: When extracting PCs from stack frames, try the `PC` field (#393)
|
|
||||||
- build: Bump gin-gonic/gin from v1.4.0 to v1.7.7 (#412)
|
|
||||||
- build: Bump Go version in go.mod (#410)
|
|
||||||
- ci: Bump golangci-lint version in GH workflow (#419)
|
|
||||||
- ci: Update GraphQL config with appropriate permissions (#417)
|
|
||||||
- ci: ci: Add craft release automation (#422)
|
|
||||||
|
|
||||||
## v0.12.0
|
|
||||||
|
|
||||||
- feat: Automatic Release detection (#363, #369, #386, #400)
|
|
||||||
- fix: Do not change Hub.lastEventID for transactions (#379)
|
|
||||||
- fix: Do not clear LastEventID when events are dropped (#382)
|
|
||||||
- Updates to documentation (#366, #385)
|
|
||||||
|
|
||||||
_NOTE:_
|
|
||||||
This version drops support for Go 1.14, however no changes have been made that would make the SDK not work with Go 1.14. The currently supported Go versions are the last 3 stable releases: 1.15, 1.16 and 1.17.
|
|
||||||
There are two behavior changes related to `LastEventID`, both of which were intended to align the behavior of the Sentry Go SDK with other Sentry SDKs.
|
|
||||||
The new [automatic release detection feature](https://github.com/getsentry/sentry-go/issues/335) makes it easier to use Sentry and separate events per release without requiring extra work from users. We intend to improve this functionality in a future release by utilizing information that will be available in runtime starting with Go 1.18. The tracking issue is [#401](https://github.com/getsentry/sentry-go/issues/401).
|
|
||||||
|
|
||||||
## v0.11.0
|
|
||||||
|
|
||||||
- feat(transports): Category-based Rate Limiting ([#354](https://github.com/getsentry/sentry-go/pull/354))
|
|
||||||
- feat(transports): Report User-Agent identifying SDK ([#357](https://github.com/getsentry/sentry-go/pull/357))
|
|
||||||
- fix(scope): Include event processors in clone ([#349](https://github.com/getsentry/sentry-go/pull/349))
|
|
||||||
- Improvements to `go doc` documentation ([#344](https://github.com/getsentry/sentry-go/pull/344), [#350](https://github.com/getsentry/sentry-go/pull/350), [#351](https://github.com/getsentry/sentry-go/pull/351))
|
|
||||||
- Miscellaneous changes to our testing infrastructure with GitHub Actions
|
|
||||||
([57123a40](https://github.com/getsentry/sentry-go/commit/57123a409be55f61b1d5a6da93c176c55a399ad0), [#128](https://github.com/getsentry/sentry-go/pull/128), [#338](https://github.com/getsentry/sentry-go/pull/338), [#345](https://github.com/getsentry/sentry-go/pull/345), [#346](https://github.com/getsentry/sentry-go/pull/346), [#352](https://github.com/getsentry/sentry-go/pull/352), [#353](https://github.com/getsentry/sentry-go/pull/353), [#355](https://github.com/getsentry/sentry-go/pull/355))
|
|
||||||
|
|
||||||
_NOTE:_
|
|
||||||
This version drops support for Go 1.13. The currently supported Go versions are the last 3 stable releases: 1.14, 1.15 and 1.16.
|
|
||||||
Users of the tracing functionality (`StartSpan`, etc) should upgrade to this version to benefit from separate rate limits for errors and transactions.
|
|
||||||
There are no breaking changes and upgrading should be a smooth experience for all users.
|
|
||||||
|
|
||||||
## v0.10.0
|
|
||||||
|
|
||||||
- feat: Debug connection reuse (#323)
|
|
||||||
- fix: Send root span data as `Event.Extra` (#329)
|
|
||||||
- fix: Do not double sample transactions (#328)
|
|
||||||
- fix: Do not override trace context of transactions (#327)
|
|
||||||
- fix: Drain and close API response bodies (#322)
|
|
||||||
- ci: Run tests against Go tip (#319)
|
|
||||||
- ci: Move away from Travis in favor of GitHub Actions (#314) (#321)
|
|
||||||
|
|
||||||
## v0.9.0
|
|
||||||
|
|
||||||
- feat: Initial tracing and performance monitoring support (#285)
|
|
||||||
- doc: Revamp sentryhttp documentation (#304)
|
|
||||||
- fix: Hub.PopScope never empties the scope stack (#300)
|
|
||||||
- ref: Report Event.Timestamp in local time (#299)
|
|
||||||
- ref: Report Breadcrumb.Timestamp in local time (#299)
|
|
||||||
|
|
||||||
_NOTE:_
|
|
||||||
This version introduces support for [Sentry's Performance Monitoring](https://docs.sentry.io/platforms/go/performance/).
|
|
||||||
The new tracing capabilities are beta, and we plan to expand them on future versions. Feedback is welcome, please open new issues on GitHub.
|
|
||||||
The `sentryhttp` package got better API docs, an [updated usage example](https://github.com/getsentry/sentry-go/tree/master/_examples/http) and support for creating automatic transactions as part of Performance Monitoring.
|
|
||||||
|
|
||||||
## v0.8.0
|
|
||||||
|
|
||||||
- build: Bump required version of Iris (#296)
|
|
||||||
- fix: avoid unnecessary allocation in Client.processEvent (#293)
|
|
||||||
- doc: Remove deprecation of sentryhttp.HandleFunc (#284)
|
|
||||||
- ref: Update sentryhttp example (#283)
|
|
||||||
- doc: Improve documentation of sentryhttp package (#282)
|
|
||||||
- doc: Clarify SampleRate documentation (#279)
|
|
||||||
- fix: Remove RawStacktrace (#278)
|
|
||||||
- docs: Add example of custom HTTP transport
|
|
||||||
- ci: Test against go1.15, drop go1.12 support (#271)
|
|
||||||
|
|
||||||
_NOTE:_
|
|
||||||
This version comes with a few updates. Some examples and documentation have been
|
|
||||||
improved. We've bumped the supported version of the Iris framework to avoid
|
|
||||||
LGPL-licensed modules in the module dependency graph.
|
|
||||||
The `Exception.RawStacktrace` and `Thread.RawStacktrace` fields have been
|
|
||||||
removed to conform to Sentry's ingestion protocol, only `Exception.Stacktrace`
|
|
||||||
and `Thread.Stacktrace` should appear in user code.
|
|
||||||
|
|
||||||
## v0.7.0
|
|
||||||
|
|
||||||
- feat: Include original error when event cannot be encoded as JSON (#258)
|
|
||||||
- feat: Use Hub from request context when available (#217, #259)
|
|
||||||
- feat: Extract stack frames from golang.org/x/xerrors (#262)
|
|
||||||
- feat: Make Environment Integration preserve existing context data (#261)
|
|
||||||
- feat: Recover and RecoverWithContext with arbitrary types (#268)
|
|
||||||
- feat: Report bad usage of CaptureMessage and CaptureEvent (#269)
|
|
||||||
- feat: Send debug logging to stderr by default (#266)
|
|
||||||
- feat: Several improvements to documentation (#223, #245, #250, #265)
|
|
||||||
- feat: Example of Recover followed by panic (#241, #247)
|
|
||||||
- feat: Add Transactions and Spans (to support OpenTelemetry Sentry Exporter) (#235, #243, #254)
|
|
||||||
- fix: Set either Frame.Filename or Frame.AbsPath (#233)
|
|
||||||
- fix: Clone requestBody to new Scope (#244)
|
|
||||||
- fix: Synchronize access and mutation of Hub.lastEventID (#264)
|
|
||||||
- fix: Avoid repeated syscalls in prepareEvent (#256)
|
|
||||||
- fix: Do not allocate new RNG for every event (#256)
|
|
||||||
- fix: Remove stale replace directive in go.mod (#255)
|
|
||||||
- fix(http): Deprecate HandleFunc, remove duplication (#260)
|
|
||||||
|
|
||||||
_NOTE:_
|
|
||||||
This version comes packed with several fixes and improvements and no breaking
|
|
||||||
changes.
|
|
||||||
Notably, there is a change in how the SDK reports file names in stack traces
|
|
||||||
that should resolve any ambiguity when looking at stack traces and using the
|
|
||||||
Suspect Commits feature.
|
|
||||||
We recommend all users to upgrade.
|
|
||||||
|
|
||||||
## v0.6.1
|
|
||||||
|
|
||||||
- fix: Use NewEvent to init Event struct (#220)
|
|
||||||
|
|
||||||
_NOTE:_
|
|
||||||
A change introduced in v0.6.0 with the intent of avoiding allocations made a
|
|
||||||
pattern used in official examples break in certain circumstances (attempting
|
|
||||||
to write to a nil map).
|
|
||||||
This release reverts the change such that maps in the Event struct are always
|
|
||||||
allocated.
|
|
||||||
|
|
||||||
## v0.6.0
|
|
||||||
|
|
||||||
- feat: Read module dependencies from runtime/debug (#199)
|
|
||||||
- feat: Support chained errors using Unwrap (#206)
|
|
||||||
- feat: Report chain of errors when available (#185)
|
|
||||||
- **[breaking]** fix: Accept http.RoundTripper to customize transport (#205)
|
|
||||||
Before the SDK accepted a concrete value of type `*http.Transport` in
|
|
||||||
`ClientOptions`, now it accepts any value implementing the `http.RoundTripper`
|
|
||||||
interface. Note that `*http.Transport` implements `http.RoundTripper`, so most
|
|
||||||
code bases will continue to work unchanged.
|
|
||||||
Users of custom transport gain the ability to pass in other implementations of
|
|
||||||
`http.RoundTripper` and may be able to simplify their code bases.
|
|
||||||
- fix: Do not panic when scope event processor drops event (#192)
|
|
||||||
- **[breaking]** fix: Use time.Time for timestamps (#191)
|
|
||||||
Users of sentry-go typically do not need to manipulate timestamps manually.
|
|
||||||
For those who do, the field type changed from `int64` to `time.Time`, which
|
|
||||||
should be more convenient to use. The recommended way to get the current time
|
|
||||||
is `time.Now().UTC()`.
|
|
||||||
- fix: Report usage error including stack trace (#189)
|
|
||||||
- feat: Add Exception.ThreadID field (#183)
|
|
||||||
- ci: Test against Go 1.14, drop 1.11 (#170)
|
|
||||||
- feat: Limit reading bytes from request bodies (#168)
|
|
||||||
- **[breaking]** fix: Rename fasthttp integration package sentryhttp => sentryfasthttp
|
|
||||||
The current recommendation is to use a named import, in which case existing
|
|
||||||
code should not require any change:
|
|
||||||
```go
|
|
||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
|
|
||||||
"github.com/getsentry/sentry-go"
|
|
||||||
sentryfasthttp "github.com/getsentry/sentry-go/fasthttp"
|
|
||||||
"github.com/valyala/fasthttp"
|
|
||||||
)
|
|
||||||
```
|
|
||||||
|
|
||||||
_NOTE:_
|
|
||||||
This version includes some new features and a few breaking changes, none of
|
|
||||||
which should pose troubles with upgrading. Most code bases should be able to
|
|
||||||
upgrade without any changes.
|
|
||||||
|
|
||||||
## v0.5.1
|
|
||||||
|
|
||||||
- fix: Ignore err.Cause() when it is nil (#160)
|
|
||||||
|
|
||||||
## v0.5.0
|
|
||||||
|
|
||||||
- fix: Synchronize access to HTTPTransport.disabledUntil (#158)
|
|
||||||
- docs: Update Flush documentation (#153)
|
|
||||||
- fix: HTTPTransport.Flush panic and data race (#140)
|
|
||||||
|
|
||||||
_NOTE:_
|
|
||||||
This version changes the implementation of the default transport, modifying the
|
|
||||||
behavior of `sentry.Flush`. The previous behavior was to wait until there were
|
|
||||||
no buffered events; new concurrent events kept `Flush` from returning. The new
|
|
||||||
behavior is to wait until the last event prior to the call to `Flush` has been
|
|
||||||
sent or the timeout; new concurrent events have no effect. The new behavior is
|
|
||||||
inline with the [Unified API
|
|
||||||
Guidelines](https://docs.sentry.io/development/sdk-dev/unified-api/).
|
|
||||||
|
|
||||||
We have updated the documentation and examples to clarify that `Flush` is meant
|
|
||||||
to be called typically only once before program termination, to wait for
|
|
||||||
in-flight events to be sent to Sentry. Calling `Flush` after every event is not
|
|
||||||
recommended, as it introduces unnecessary latency to the surrounding function.
|
|
||||||
Please verify the usage of `sentry.Flush` in your code base.
|
|
||||||
|
|
||||||
## v0.4.0
|
|
||||||
|
|
||||||
- fix(stacktrace): Correctly report package names (#127)
|
|
||||||
- fix(stacktrace): Do not rely on AbsPath of files (#123)
|
|
||||||
- build: Require github.com/ugorji/go@v1.1.7 (#110)
|
|
||||||
- fix: Correctly store last event id (#99)
|
|
||||||
- fix: Include request body in event payload (#94)
|
|
||||||
- build: Reset go.mod version to 1.11 (#109)
|
|
||||||
- fix: Eliminate data race in modules integration (#105)
|
|
||||||
- feat: Add support for path prefixes in the DSN (#102)
|
|
||||||
- feat: Add HTTPClient option (#86)
|
|
||||||
- feat: Extract correct type and value from top-most error (#85)
|
|
||||||
- feat: Check for broken pipe errors in Gin integration (#82)
|
|
||||||
- fix: Client.CaptureMessage accept nil EventModifier (#72)
|
|
||||||
|
|
||||||
## v0.3.1
|
|
||||||
|
|
||||||
- feat: Send extra information exposed by the Go runtime (#76)
|
|
||||||
- fix: Handle new lines in module integration (#65)
|
|
||||||
- fix: Make sure that cache is locked when updating for contextifyFramesIntegration
|
|
||||||
- ref: Update Iris integration and example to version 12
|
|
||||||
- misc: Remove indirect dependencies in order to move them to separate go.mod files
|
|
||||||
|
|
||||||
## v0.3.0
|
|
||||||
|
|
||||||
- feat: Retry event marshaling without contextual data if the first pass fails
|
|
||||||
- fix: Include `url.Parse` error in `DsnParseError`
|
|
||||||
- fix: Make more `Scope` methods safe for concurrency
|
|
||||||
- fix: Synchronize concurrent access to `Hub.client`
|
|
||||||
- ref: Remove mutex from `Scope` exported API
|
|
||||||
- ref: Remove mutex from `Hub` exported API
|
|
||||||
- ref: Compile regexps for `filterFrames` only once
|
|
||||||
- ref: Change `SampleRate` type to `float64`
|
|
||||||
- doc: `Scope.Clear` not safe for concurrent use
|
|
||||||
- ci: Test sentry-go with `go1.13`, drop `go1.10`
|
|
||||||
|
|
||||||
_NOTE:_
|
|
||||||
This version removes some of the internal APIs that landed publicly (namely `Hub/Scope` mutex structs) and may require (but shouldn't) some changes to your code.
|
|
||||||
It's not done through major version update, as we are still in `0.x` stage.
|
|
||||||
|
|
||||||
## v0.2.1
|
|
||||||
|
|
||||||
- fix: Run `Contextify` integration on `Threads` as well
|
|
||||||
|
|
||||||
## v0.2.0
|
|
||||||
|
|
||||||
- feat: Add `SetTransaction()` method on the `Scope`
|
|
||||||
- feat: `fasthttp` framework support with `sentryfasthttp` package
|
|
||||||
- fix: Add `RWMutex` locks to internal `Hub` and `Scope` changes
|
|
||||||
|
|
||||||
## v0.1.3
|
|
||||||
|
|
||||||
- feat: Move frames context reading into `contextifyFramesIntegration` (#28)
|
|
||||||
|
|
||||||
_NOTE:_
|
|
||||||
In case of any performance issues due to source contexts IO, you can let us know and turn off the integration in the meantime with:
|
|
||||||
|
|
||||||
```go
|
|
||||||
sentry.Init(sentry.ClientOptions{
|
|
||||||
Integrations: func(integrations []sentry.Integration) []sentry.Integration {
|
|
||||||
var filteredIntegrations []sentry.Integration
|
|
||||||
for _, integration := range integrations {
|
|
||||||
if integration.Name() == "ContextifyFrames" {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
filteredIntegrations = append(filteredIntegrations, integration)
|
|
||||||
}
|
|
||||||
return filteredIntegrations
|
|
||||||
},
|
|
||||||
})
|
|
||||||
```
|
|
||||||
|
|
||||||
## v0.1.2
|
|
||||||
|
|
||||||
- feat: Better source code location resolution and more useful inapp frames (#26)
|
|
||||||
- feat: Use `noopTransport` when no `Dsn` provided (#27)
|
|
||||||
- ref: Allow empty `Dsn` instead of returning an error (#22)
|
|
||||||
- fix: Use `NewScope` instead of literal struct inside a `scope.Clear` call (#24)
|
|
||||||
- fix: Add to `WaitGroup` before the request is put inside a buffer (#25)
|
|
||||||
|
|
||||||
## v0.1.1
|
|
||||||
|
|
||||||
- fix: Check for initialized `Client` in `AddBreadcrumbs` (#20)
|
|
||||||
- build: Bump version when releasing with Craft (#19)
|
|
||||||
|
|
||||||
## v0.1.0
|
|
||||||
|
|
||||||
- First stable release! \o/
|
|
||||||
|
|
||||||
## v0.0.1-beta.5
|
|
||||||
|
|
||||||
- feat: **[breaking]** Add `NewHTTPTransport` and `NewHTTPSyncTransport` which accepts all transport options
|
|
||||||
- feat: New `HTTPSyncTransport` that blocks after each call
|
|
||||||
- feat: New `Echo` integration
|
|
||||||
- ref: **[breaking]** Remove `BufferSize` option from `ClientOptions` and move it to `HTTPTransport` instead
|
|
||||||
- ref: Export default `HTTPTransport`
|
|
||||||
- ref: Export `net/http` integration handler
|
|
||||||
- ref: Set `Request` instantly in the package handlers, not in `recoverWithSentry` so it can be accessed later on
|
|
||||||
- ci: Add craft config
|
|
||||||
|
|
||||||
## v0.0.1-beta.4
|
|
||||||
|
|
||||||
- feat: `IgnoreErrors` client option and corresponding integration
|
|
||||||
- ref: Reworked `net/http` integration, wrote better example and complete readme
|
|
||||||
- ref: Reworked `Gin` integration, wrote better example and complete readme
|
|
||||||
- ref: Reworked `Iris` integration, wrote better example and complete readme
|
|
||||||
- ref: Reworked `Negroni` integration, wrote better example and complete readme
|
|
||||||
- ref: Reworked `Martini` integration, wrote better example and complete readme
|
|
||||||
- ref: Remove `Handle()` from frameworks handlers and return it directly from New
|
|
||||||
|
|
||||||
## v0.0.1-beta.3
|
|
||||||
|
|
||||||
- feat: `Iris` framework support with `sentryiris` package
|
|
||||||
- feat: `Gin` framework support with `sentrygin` package
|
|
||||||
- feat: `Martini` framework support with `sentrymartini` package
|
|
||||||
- feat: `Negroni` framework support with `sentrynegroni` package
|
|
||||||
- feat: Add `Hub.Clone()` for easier frameworks integration
|
|
||||||
- feat: Return `EventID` from `Recovery` methods
|
|
||||||
- feat: Add `NewScope` and `NewEvent` functions and use them in the whole codebase
|
|
||||||
- feat: Add `AddEventProcessor` to the `Client`
|
|
||||||
- fix: Operate on requests body copy instead of the original
|
|
||||||
- ref: Try to read source files from the root directory, based on the filename as well, to make it work on AWS Lambda
|
|
||||||
- ref: Remove `gocertifi` dependence and document how to provide your own certificates
|
|
||||||
- ref: **[breaking]** Remove `Decorate` and `DecorateFunc` methods in favor of `sentryhttp` package
|
|
||||||
- ref: **[breaking]** Allow for integrations to live on the client, by passing client instance in `SetupOnce` method
|
|
||||||
- ref: **[breaking]** Remove `GetIntegration` from the `Hub`
|
|
||||||
- ref: **[breaking]** Remove `GlobalEventProcessors` getter from the public API
|
|
||||||
|
|
||||||
## v0.0.1-beta.2
|
|
||||||
|
|
||||||
- feat: Add `AttachStacktrace` client option to include stacktrace for messages
|
|
||||||
- feat: Add `BufferSize` client option to configure transport buffer size
|
|
||||||
- feat: Add `SetRequest` method on a `Scope` to control `Request` context data
|
|
||||||
- feat: Add `FromHTTPRequest` for `Request` type for easier extraction
|
|
||||||
- ref: Extract `Request` information more accurately
|
|
||||||
- fix: Attach `ServerName`, `Release`, `Dist`, `Environment` options to the event
|
|
||||||
- fix: Don't log events dropped due to full transport buffer as sent
|
|
||||||
- fix: Don't panic and create an appropriate event when called `CaptureException` or `Recover` with `nil` value
|
|
||||||
|
|
||||||
## v0.0.1-beta
|
|
||||||
|
|
||||||
- Initial release
|
|
||||||
-98
@@ -1,98 +0,0 @@
|
|||||||
# Contributing to sentry-go
|
|
||||||
|
|
||||||
Hey, thank you if you're reading this, we welcome your contribution!
|
|
||||||
|
|
||||||
## Sending a Pull Request
|
|
||||||
|
|
||||||
Please help us save time when reviewing your PR by following this simple
|
|
||||||
process:
|
|
||||||
|
|
||||||
1. Is your PR a simple typo fix? Read no further, **click that green "Create
|
|
||||||
pull request" button**!
|
|
||||||
|
|
||||||
2. For more complex PRs that involve behavior changes or new APIs, please
|
|
||||||
consider [opening an **issue**][new-issue] describing the problem you're
|
|
||||||
trying to solve if there's not one already.
|
|
||||||
|
|
||||||
A PR is often one specific solution to a problem and sometimes talking about
|
|
||||||
the problem unfolds new possible solutions. Remember we will be responsible
|
|
||||||
for maintaining the changes later.
|
|
||||||
|
|
||||||
3. Fixing a bug and changing a behavior? Please add automated tests to prevent
|
|
||||||
future regression.
|
|
||||||
|
|
||||||
4. Practice writing good commit messages. We have [commit
|
|
||||||
guidelines][commit-guide].
|
|
||||||
|
|
||||||
5. We have [guidelines for PR submitters][pr-guide]. A short summary:
|
|
||||||
|
|
||||||
- Good PR descriptions are very helpful and most of the time they include
|
|
||||||
**why** something is done and why done in this particular way. Also list
|
|
||||||
other possible solutions that were considered and discarded.
|
|
||||||
- Be your own first reviewer. Make sure your code compiles and passes the
|
|
||||||
existing tests.
|
|
||||||
|
|
||||||
[new-issue]: https://github.com/getsentry/sentry-go/issues/new/choose
|
|
||||||
[commit-guide]: https://develop.sentry.dev/code-review/#commit-guidelines
|
|
||||||
[pr-guide]: https://develop.sentry.dev/code-review/#guidelines-for-submitters
|
|
||||||
|
|
||||||
Please also read through our [SDK Development docs](https://develop.sentry.dev/sdk/).
|
|
||||||
It contains information about SDK features, expected payloads and best practices for
|
|
||||||
contributing to Sentry SDKs.
|
|
||||||
|
|
||||||
## Community
|
|
||||||
|
|
||||||
The public-facing channels for support and development of Sentry SDKs can be found on [Discord](https://discord.gg/Ww9hbqr).
|
|
||||||
|
|
||||||
## Testing
|
|
||||||
|
|
||||||
```console
|
|
||||||
$ go test
|
|
||||||
```
|
|
||||||
|
|
||||||
### Watch mode
|
|
||||||
|
|
||||||
Use: https://github.com/cespare/reflex
|
|
||||||
|
|
||||||
```console
|
|
||||||
$ reflex -g '*.go' -d "none" -- sh -c 'printf "\n"; go test'
|
|
||||||
```
|
|
||||||
|
|
||||||
### With data race detection
|
|
||||||
|
|
||||||
```console
|
|
||||||
$ go test -race
|
|
||||||
```
|
|
||||||
|
|
||||||
### Coverage
|
|
||||||
|
|
||||||
```console
|
|
||||||
$ go test -race -coverprofile=coverage.txt -covermode=atomic && go tool cover -html coverage.txt
|
|
||||||
```
|
|
||||||
|
|
||||||
## Linting
|
|
||||||
|
|
||||||
Lint with [`golangci-lint`](https://github.com/golangci/golangci-lint):
|
|
||||||
|
|
||||||
```console
|
|
||||||
$ golangci-lint run
|
|
||||||
```
|
|
||||||
|
|
||||||
## Release
|
|
||||||
|
|
||||||
1. Update `CHANGELOG.md` with new version in `vX.X.X` format title and list of changes.
|
|
||||||
|
|
||||||
The command below can be used to get a list of changes since the last tag, with the format used in `CHANGELOG.md`:
|
|
||||||
|
|
||||||
```console
|
|
||||||
$ git log --no-merges --format=%s $(git describe --abbrev=0).. | sed 's/^/- /'
|
|
||||||
```
|
|
||||||
|
|
||||||
2. Commit with `misc: vX.X.X changelog` commit message and push to `master`.
|
|
||||||
|
|
||||||
3. Let [`craft`](https://github.com/getsentry/craft) do the rest:
|
|
||||||
|
|
||||||
```console
|
|
||||||
$ craft prepare X.X.X
|
|
||||||
$ craft publish X.X.X
|
|
||||||
```
|
|
||||||
-21
@@ -1,21 +0,0 @@
|
|||||||
MIT License
|
|
||||||
|
|
||||||
Copyright (c) 2019 Functional Software, Inc. dba Sentry
|
|
||||||
|
|
||||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
||||||
of this software and associated documentation files (the "Software"), to deal
|
|
||||||
in the Software without restriction, including without limitation the rights
|
|
||||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
||||||
copies of the Software, and to permit persons to whom the Software is
|
|
||||||
furnished to do so, subject to the following conditions:
|
|
||||||
|
|
||||||
The above copyright notice and this permission notice shall be included in all
|
|
||||||
copies or substantial portions of the Software.
|
|
||||||
|
|
||||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
||||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
||||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
||||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
||||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
||||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
||||||
SOFTWARE.
|
|
||||||
-3
@@ -1,3 +0,0 @@
|
|||||||
# `raven-go` to `sentry-go` Migration Guide
|
|
||||||
|
|
||||||
A [`raven-go` to `sentry-go` migration guide](https://docs.sentry.io/platforms/go/migration/) is available at the official Sentry documentation site.
|
|
||||||
-82
@@ -1,82 +0,0 @@
|
|||||||
.DEFAULT_GOAL := help
|
|
||||||
|
|
||||||
MKFILE_PATH := $(abspath $(lastword $(MAKEFILE_LIST)))
|
|
||||||
MKFILE_DIR := $(dir $(MKFILE_PATH))
|
|
||||||
ALL_GO_MOD_DIRS := $(shell find . -type f -name 'go.mod' -exec dirname {} \; | sort)
|
|
||||||
GO = go
|
|
||||||
TIMEOUT = 300
|
|
||||||
|
|
||||||
# Parse Makefile and display the help
|
|
||||||
help: ## Show help
|
|
||||||
@grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}'
|
|
||||||
.PHONY: help
|
|
||||||
|
|
||||||
build: ## Build everything
|
|
||||||
for dir in $(ALL_GO_MOD_DIRS); do \
|
|
||||||
cd "$${dir}"; \
|
|
||||||
echo ">>> Running 'go build' for module: $${dir}"; \
|
|
||||||
go build ./...; \
|
|
||||||
done;
|
|
||||||
.PHONY: build
|
|
||||||
|
|
||||||
### Tests (inspired by https://github.com/open-telemetry/opentelemetry-go/blob/main/Makefile)
|
|
||||||
TEST_TARGETS := test-short test-verbose test-race
|
|
||||||
test-race: ARGS=-race
|
|
||||||
test-short: ARGS=-short
|
|
||||||
test-verbose: ARGS=-v -race
|
|
||||||
$(TEST_TARGETS): test
|
|
||||||
test: $(ALL_GO_MOD_DIRS:%=test/%) ## Run tests
|
|
||||||
test/%: DIR=$*
|
|
||||||
test/%:
|
|
||||||
@echo ">>> Running tests for module: $(DIR)"
|
|
||||||
@# We use '-count=1' to disable test caching.
|
|
||||||
(cd $(DIR) && $(GO) test -count=1 -timeout $(TIMEOUT)s $(ARGS) ./...)
|
|
||||||
.PHONY: $(TEST_TARGETS) test
|
|
||||||
|
|
||||||
# Coverage
|
|
||||||
COVERAGE_MODE = atomic
|
|
||||||
COVERAGE_PROFILE = coverage.out
|
|
||||||
COVERAGE_REPORT_DIR = .coverage
|
|
||||||
COVERAGE_REPORT_DIR_ABS = "$(MKFILE_DIR)/$(COVERAGE_REPORT_DIR)"
|
|
||||||
$(COVERAGE_REPORT_DIR):
|
|
||||||
mkdir -p $(COVERAGE_REPORT_DIR)
|
|
||||||
clean-report-dir: $(COVERAGE_REPORT_DIR)
|
|
||||||
test $(COVERAGE_REPORT_DIR) && rm -f $(COVERAGE_REPORT_DIR)/*
|
|
||||||
test-coverage: $(COVERAGE_REPORT_DIR) clean-report-dir ## Test with coverage enabled
|
|
||||||
set -e ; \
|
|
||||||
for dir in $(ALL_GO_MOD_DIRS); do \
|
|
||||||
echo ">>> Running tests with coverage for module: $${dir}"; \
|
|
||||||
DIR_ABS=$$(python -c 'import os, sys; print(os.path.realpath(sys.argv[1]))' $${dir}) ; \
|
|
||||||
REPORT_NAME=$$(basename $${DIR_ABS}); \
|
|
||||||
(cd "$${dir}" && \
|
|
||||||
$(GO) test -count=1 -timeout $(TIMEOUT)s -coverpkg=./... -covermode=$(COVERAGE_MODE) -coverprofile="$(COVERAGE_PROFILE)" ./... && \
|
|
||||||
cp $(COVERAGE_PROFILE) "$(COVERAGE_REPORT_DIR_ABS)/$${REPORT_NAME}_$(COVERAGE_PROFILE)" && \
|
|
||||||
$(GO) tool cover -html=$(COVERAGE_PROFILE) -o coverage.html); \
|
|
||||||
done;
|
|
||||||
.PHONY: test-coverage clean-report-dir
|
|
||||||
|
|
||||||
mod-tidy: ## Check go.mod tidiness
|
|
||||||
set -e ; \
|
|
||||||
for dir in $(ALL_GO_MOD_DIRS); do \
|
|
||||||
echo ">>> Running 'go mod tidy' for module: $${dir}"; \
|
|
||||||
(cd "$${dir}" && go mod tidy -go=1.21 -compat=1.21); \
|
|
||||||
done; \
|
|
||||||
git diff --exit-code;
|
|
||||||
.PHONY: mod-tidy
|
|
||||||
|
|
||||||
vet: ## Run "go vet"
|
|
||||||
set -e ; \
|
|
||||||
for dir in $(ALL_GO_MOD_DIRS); do \
|
|
||||||
echo ">>> Running 'go vet' for module: $${dir}"; \
|
|
||||||
(cd "$${dir}" && go vet ./...); \
|
|
||||||
done;
|
|
||||||
.PHONY: vet
|
|
||||||
|
|
||||||
|
|
||||||
lint: ## Lint (using "golangci-lint")
|
|
||||||
golangci-lint run
|
|
||||||
.PHONY: lint
|
|
||||||
|
|
||||||
fmt: ## Format all Go files
|
|
||||||
gofmt -l -w -s .
|
|
||||||
.PHONY: fmt
|
|
||||||
-106
@@ -1,106 +0,0 @@
|
|||||||
<p align="center">
|
|
||||||
<a href="https://sentry.io/?utm_source=github&utm_medium=logo" target="_blank">
|
|
||||||
<picture>
|
|
||||||
<source srcset="https://sentry-brand.storage.googleapis.com/sentry-logo-white.png" media="(prefers-color-scheme: dark)" />
|
|
||||||
<source srcset="https://sentry-brand.storage.googleapis.com/sentry-logo-black.png" media="(prefers-color-scheme: light), (prefers-color-scheme: no-preference)" />
|
|
||||||
<img src="https://sentry-brand.storage.googleapis.com/sentry-logo-black.png" alt="Sentry" width="280">
|
|
||||||
</picture>
|
|
||||||
</a>
|
|
||||||
</p>
|
|
||||||
|
|
||||||
# Official Sentry SDK for Go
|
|
||||||
|
|
||||||
[](https://github.com/getsentry/sentry-go/actions/workflows/test.yml)
|
|
||||||
[](https://goreportcard.com/report/github.com/getsentry/sentry-go)
|
|
||||||
[](https://discord.gg/Ww9hbqr)
|
|
||||||
[](https://pkg.go.dev/github.com/getsentry/sentry-go)
|
|
||||||
|
|
||||||
`sentry-go` provides a Sentry client implementation for the Go programming
|
|
||||||
language. This is the next generation of the Go SDK for [Sentry](https://sentry.io/),
|
|
||||||
intended to replace the `raven-go` package.
|
|
||||||
|
|
||||||
> Looking for the old `raven-go` SDK documentation? See the Legacy client section [here](https://docs.sentry.io/clients/go/).
|
|
||||||
> If you want to start using `sentry-go` instead, check out the [migration guide](https://docs.sentry.io/platforms/go/migration/).
|
|
||||||
|
|
||||||
## Requirements
|
|
||||||
|
|
||||||
The only requirement is a Go compiler.
|
|
||||||
|
|
||||||
We verify this package against the 3 most recent releases of Go. Those are the
|
|
||||||
supported versions. The exact versions are defined in
|
|
||||||
[`GitHub workflow`](.github/workflows/test.yml).
|
|
||||||
|
|
||||||
In addition, we run tests against the current master branch of the Go toolchain,
|
|
||||||
though support for this configuration is best-effort.
|
|
||||||
|
|
||||||
## Installation
|
|
||||||
|
|
||||||
`sentry-go` can be installed like any other Go library through `go get`:
|
|
||||||
|
|
||||||
```console
|
|
||||||
$ go get github.com/getsentry/sentry-go@latest
|
|
||||||
```
|
|
||||||
|
|
||||||
Check out the [list of released versions](https://github.com/getsentry/sentry-go/releases).
|
|
||||||
|
|
||||||
## Configuration
|
|
||||||
|
|
||||||
To use `sentry-go`, you’ll need to import the `sentry-go` package and initialize
|
|
||||||
it with your DSN and other [options](https://pkg.go.dev/github.com/getsentry/sentry-go#ClientOptions).
|
|
||||||
|
|
||||||
If not specified in the SDK initialization, the
|
|
||||||
[DSN](https://docs.sentry.io/product/sentry-basics/dsn-explainer/),
|
|
||||||
[Release](https://docs.sentry.io/product/releases/) and
|
|
||||||
[Environment](https://docs.sentry.io/product/sentry-basics/environments/)
|
|
||||||
are read from the environment variables `SENTRY_DSN`, `SENTRY_RELEASE` and
|
|
||||||
`SENTRY_ENVIRONMENT`, respectively.
|
|
||||||
|
|
||||||
More on this in the [Configuration section of the official Sentry Go SDK documentation](https://docs.sentry.io/platforms/go/configuration/).
|
|
||||||
|
|
||||||
## Usage
|
|
||||||
|
|
||||||
The SDK supports reporting errors and tracking application performance.
|
|
||||||
|
|
||||||
To get started, have a look at one of our [examples](_examples/):
|
|
||||||
- [Basic error instrumentation](_examples/basic/main.go)
|
|
||||||
- [Error and tracing for HTTP servers](_examples/http/main.go)
|
|
||||||
|
|
||||||
We also provide a [complete API reference](https://pkg.go.dev/github.com/getsentry/sentry-go).
|
|
||||||
|
|
||||||
For more detailed information about how to get the most out of `sentry-go`,
|
|
||||||
check out the official documentation:
|
|
||||||
|
|
||||||
- [Sentry Go SDK documentation](https://docs.sentry.io/platforms/go/)
|
|
||||||
- Guides:
|
|
||||||
- [net/http](https://docs.sentry.io/platforms/go/guides/http/)
|
|
||||||
- [echo](https://docs.sentry.io/platforms/go/guides/echo/)
|
|
||||||
- [fasthttp](https://docs.sentry.io/platforms/go/guides/fasthttp/)
|
|
||||||
- [fiber](https://docs.sentry.io/platforms/go/guides/fiber/)
|
|
||||||
- [gin](https://docs.sentry.io/platforms/go/guides/gin/)
|
|
||||||
- [iris](https://docs.sentry.io/platforms/go/guides/iris/)
|
|
||||||
- [logrus](https://docs.sentry.io/platforms/go/guides/logrus/)
|
|
||||||
- [negroni](https://docs.sentry.io/platforms/go/guides/negroni/)
|
|
||||||
- [slog](https://docs.sentry.io/platforms/go/guides/slog/)
|
|
||||||
- [zerolog](https://docs.sentry.io/platforms/go/guides/zerolog/)
|
|
||||||
|
|
||||||
## Resources
|
|
||||||
|
|
||||||
- [Bug Tracker](https://github.com/getsentry/sentry-go/issues)
|
|
||||||
- [GitHub Project](https://github.com/getsentry/sentry-go)
|
|
||||||
- [](https://pkg.go.dev/github.com/getsentry/sentry-go)
|
|
||||||
- [](https://docs.sentry.io/platforms/go/)
|
|
||||||
- [](https://github.com/getsentry/sentry-go/discussions)
|
|
||||||
- [](https://discord.gg/Ww9hbqr)
|
|
||||||
- [](http://stackoverflow.com/questions/tagged/sentry)
|
|
||||||
- [](https://twitter.com/intent/follow?screen_name=getsentry)
|
|
||||||
|
|
||||||
## License
|
|
||||||
|
|
||||||
Licensed under
|
|
||||||
[The MIT License](https://opensource.org/licenses/mit/), see
|
|
||||||
[`LICENSE`](LICENSE).
|
|
||||||
|
|
||||||
## Community
|
|
||||||
|
|
||||||
Join Sentry's [`#go` channel on Discord](https://discord.gg/Ww9hbqr) to get
|
|
||||||
involved and help us improve the SDK!
|
|
||||||
-121
@@ -1,121 +0,0 @@
|
|||||||
package sentry
|
|
||||||
|
|
||||||
import "time"
|
|
||||||
|
|
||||||
type CheckInStatus string
|
|
||||||
|
|
||||||
const (
|
|
||||||
CheckInStatusInProgress CheckInStatus = "in_progress"
|
|
||||||
CheckInStatusOK CheckInStatus = "ok"
|
|
||||||
CheckInStatusError CheckInStatus = "error"
|
|
||||||
)
|
|
||||||
|
|
||||||
type checkInScheduleType string
|
|
||||||
|
|
||||||
const (
|
|
||||||
checkInScheduleTypeCrontab checkInScheduleType = "crontab"
|
|
||||||
checkInScheduleTypeInterval checkInScheduleType = "interval"
|
|
||||||
)
|
|
||||||
|
|
||||||
type MonitorSchedule interface {
|
|
||||||
// scheduleType is a private method that must be implemented for monitor schedule
|
|
||||||
// implementation. It should never be called. This method is made for having
|
|
||||||
// specific private implementation of MonitorSchedule interface.
|
|
||||||
scheduleType() checkInScheduleType
|
|
||||||
}
|
|
||||||
|
|
||||||
type crontabSchedule struct {
|
|
||||||
Type string `json:"type"`
|
|
||||||
Value string `json:"value"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c crontabSchedule) scheduleType() checkInScheduleType {
|
|
||||||
return checkInScheduleTypeCrontab
|
|
||||||
}
|
|
||||||
|
|
||||||
// CrontabSchedule defines the MonitorSchedule with a cron format.
|
|
||||||
// Example: "8 * * * *".
|
|
||||||
func CrontabSchedule(scheduleString string) MonitorSchedule {
|
|
||||||
return crontabSchedule{
|
|
||||||
Type: string(checkInScheduleTypeCrontab),
|
|
||||||
Value: scheduleString,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
type intervalSchedule struct {
|
|
||||||
Type string `json:"type"`
|
|
||||||
Value int64 `json:"value"`
|
|
||||||
Unit string `json:"unit"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (i intervalSchedule) scheduleType() checkInScheduleType {
|
|
||||||
return checkInScheduleTypeInterval
|
|
||||||
}
|
|
||||||
|
|
||||||
type MonitorScheduleUnit string
|
|
||||||
|
|
||||||
const (
|
|
||||||
MonitorScheduleUnitMinute MonitorScheduleUnit = "minute"
|
|
||||||
MonitorScheduleUnitHour MonitorScheduleUnit = "hour"
|
|
||||||
MonitorScheduleUnitDay MonitorScheduleUnit = "day"
|
|
||||||
MonitorScheduleUnitWeek MonitorScheduleUnit = "week"
|
|
||||||
MonitorScheduleUnitMonth MonitorScheduleUnit = "month"
|
|
||||||
MonitorScheduleUnitYear MonitorScheduleUnit = "year"
|
|
||||||
)
|
|
||||||
|
|
||||||
// IntervalSchedule defines the MonitorSchedule with an interval format.
|
|
||||||
//
|
|
||||||
// Example:
|
|
||||||
//
|
|
||||||
// IntervalSchedule(1, sentry.MonitorScheduleUnitDay)
|
|
||||||
func IntervalSchedule(value int64, unit MonitorScheduleUnit) MonitorSchedule {
|
|
||||||
return intervalSchedule{
|
|
||||||
Type: string(checkInScheduleTypeInterval),
|
|
||||||
Value: value,
|
|
||||||
Unit: string(unit),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
type MonitorConfig struct { //nolint: maligned // prefer readability over optimal memory layout
|
|
||||||
Schedule MonitorSchedule `json:"schedule,omitempty"`
|
|
||||||
// The allowed margin of minutes after the expected check-in time that
|
|
||||||
// the monitor will not be considered missed for.
|
|
||||||
CheckInMargin int64 `json:"checkin_margin,omitempty"`
|
|
||||||
// The allowed duration in minutes that the monitor may be `in_progress`
|
|
||||||
// for before being considered failed due to timeout.
|
|
||||||
MaxRuntime int64 `json:"max_runtime,omitempty"`
|
|
||||||
// A tz database string representing the timezone which the monitor's execution schedule is in.
|
|
||||||
// See: https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
|
|
||||||
Timezone string `json:"timezone,omitempty"`
|
|
||||||
// The number of consecutive failed check-ins it takes before an issue is created.
|
|
||||||
FailureIssueThreshold int64 `json:"failure_issue_threshold,omitempty"`
|
|
||||||
// The number of consecutive OK check-ins it takes before an issue is resolved.
|
|
||||||
RecoveryThreshold int64 `json:"recovery_threshold,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type CheckIn struct { //nolint: maligned // prefer readability over optimal memory layout
|
|
||||||
// Check-In ID (unique and client generated)
|
|
||||||
ID EventID `json:"check_in_id"`
|
|
||||||
// The distinct slug of the monitor.
|
|
||||||
MonitorSlug string `json:"monitor_slug"`
|
|
||||||
// The status of the check-in.
|
|
||||||
Status CheckInStatus `json:"status"`
|
|
||||||
// The duration of the check-in. Will only take effect if the status is ok or error.
|
|
||||||
Duration time.Duration `json:"duration,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// serializedCheckIn is used by checkInMarshalJSON method on Event struct.
|
|
||||||
// See https://develop.sentry.dev/sdk/check-ins/
|
|
||||||
type serializedCheckIn struct { //nolint: maligned
|
|
||||||
// Check-In ID (unique and client generated).
|
|
||||||
CheckInID string `json:"check_in_id"`
|
|
||||||
// The distinct slug of the monitor.
|
|
||||||
MonitorSlug string `json:"monitor_slug"`
|
|
||||||
// The status of the check-in.
|
|
||||||
Status CheckInStatus `json:"status"`
|
|
||||||
// The duration of the check-in in seconds. Will only take effect if the status is ok or error.
|
|
||||||
Duration float64 `json:"duration,omitempty"`
|
|
||||||
Release string `json:"release,omitempty"`
|
|
||||||
Environment string `json:"environment,omitempty"`
|
|
||||||
MonitorConfig *MonitorConfig `json:"monitor_config,omitempty"`
|
|
||||||
}
|
|
||||||
-733
@@ -1,733 +0,0 @@
|
|||||||
package sentry
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"crypto/x509"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
"log"
|
|
||||||
"math/rand"
|
|
||||||
"net/http"
|
|
||||||
"os"
|
|
||||||
"sort"
|
|
||||||
"strings"
|
|
||||||
"sync"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/getsentry/sentry-go/internal/debug"
|
|
||||||
)
|
|
||||||
|
|
||||||
// The identifier of the SDK.
|
|
||||||
const sdkIdentifier = "sentry.go"
|
|
||||||
|
|
||||||
// maxErrorDepth is the maximum number of errors reported in a chain of errors.
|
|
||||||
// This protects the SDK from an arbitrarily long chain of wrapped errors.
|
|
||||||
//
|
|
||||||
// An additional consideration is that arguably reporting a long chain of errors
|
|
||||||
// is of little use when debugging production errors with Sentry. The Sentry UI
|
|
||||||
// is not optimized for long chains either. The top-level error together with a
|
|
||||||
// stack trace is often the most useful information.
|
|
||||||
const maxErrorDepth = 10
|
|
||||||
|
|
||||||
// defaultMaxSpans limits the default number of recorded spans per transaction. The limit is
|
|
||||||
// meant to bound memory usage and prevent too large transaction events that
|
|
||||||
// would be rejected by Sentry.
|
|
||||||
const defaultMaxSpans = 1000
|
|
||||||
|
|
||||||
// hostname is the host name reported by the kernel. It is precomputed once to
|
|
||||||
// avoid syscalls when capturing events.
|
|
||||||
//
|
|
||||||
// The error is ignored because retrieving the host name is best-effort. If the
|
|
||||||
// error is non-nil, there is nothing to do other than retrying. We choose not
|
|
||||||
// to retry for now.
|
|
||||||
var hostname, _ = os.Hostname()
|
|
||||||
|
|
||||||
// lockedRand is a random number generator safe for concurrent use. Its API is
|
|
||||||
// intentionally limited and it is not meant as a full replacement for a
|
|
||||||
// rand.Rand.
|
|
||||||
type lockedRand struct {
|
|
||||||
mu sync.Mutex
|
|
||||||
r *rand.Rand
|
|
||||||
}
|
|
||||||
|
|
||||||
// Float64 returns a pseudo-random number in [0.0,1.0).
|
|
||||||
func (r *lockedRand) Float64() float64 {
|
|
||||||
r.mu.Lock()
|
|
||||||
defer r.mu.Unlock()
|
|
||||||
return r.r.Float64()
|
|
||||||
}
|
|
||||||
|
|
||||||
// rng is the internal random number generator.
|
|
||||||
//
|
|
||||||
// We do not use the global functions from math/rand because, while they are
|
|
||||||
// safe for concurrent use, any package in a build could change the seed and
|
|
||||||
// affect the generated numbers, for instance making them deterministic. On the
|
|
||||||
// other hand, the source returned from rand.NewSource is not safe for
|
|
||||||
// concurrent use, so we need to couple its use with a sync.Mutex.
|
|
||||||
var rng = &lockedRand{
|
|
||||||
// #nosec G404 -- We are fine using transparent, non-secure value here.
|
|
||||||
r: rand.New(rand.NewSource(time.Now().UnixNano())),
|
|
||||||
}
|
|
||||||
|
|
||||||
// usageError is used to report to Sentry an SDK usage error.
|
|
||||||
//
|
|
||||||
// It is not exported because it is never returned by any function or method in
|
|
||||||
// the exported API.
|
|
||||||
type usageError struct {
|
|
||||||
error
|
|
||||||
}
|
|
||||||
|
|
||||||
// Logger is an instance of log.Logger that is use to provide debug information about running Sentry Client
|
|
||||||
// can be enabled by either using Logger.SetOutput directly or with Debug client option.
|
|
||||||
var Logger = log.New(io.Discard, "[Sentry] ", log.LstdFlags)
|
|
||||||
|
|
||||||
// EventProcessor is a function that processes an event.
|
|
||||||
// Event processors are used to change an event before it is sent to Sentry.
|
|
||||||
type EventProcessor func(event *Event, hint *EventHint) *Event
|
|
||||||
|
|
||||||
// EventModifier is the interface that wraps the ApplyToEvent method.
|
|
||||||
//
|
|
||||||
// ApplyToEvent changes an event based on external data and/or
|
|
||||||
// an event hint.
|
|
||||||
type EventModifier interface {
|
|
||||||
ApplyToEvent(event *Event, hint *EventHint, client *Client) *Event
|
|
||||||
}
|
|
||||||
|
|
||||||
var globalEventProcessors []EventProcessor
|
|
||||||
|
|
||||||
// AddGlobalEventProcessor adds processor to the global list of event
|
|
||||||
// processors. Global event processors apply to all events.
|
|
||||||
//
|
|
||||||
// AddGlobalEventProcessor is deprecated. Most users will prefer to initialize
|
|
||||||
// the SDK with Init and provide a ClientOptions.BeforeSend function or use
|
|
||||||
// Scope.AddEventProcessor instead.
|
|
||||||
func AddGlobalEventProcessor(processor EventProcessor) {
|
|
||||||
globalEventProcessors = append(globalEventProcessors, processor)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Integration allows for registering a functions that modify or discard captured events.
|
|
||||||
type Integration interface {
|
|
||||||
Name() string
|
|
||||||
SetupOnce(client *Client)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ClientOptions that configures a SDK Client.
|
|
||||||
type ClientOptions struct {
|
|
||||||
// The DSN to use. If the DSN is not set, the client is effectively
|
|
||||||
// disabled.
|
|
||||||
Dsn string
|
|
||||||
// In debug mode, the debug information is printed to stdout to help you
|
|
||||||
// understand what sentry is doing.
|
|
||||||
Debug bool
|
|
||||||
// Configures whether SDK should generate and attach stacktraces to pure
|
|
||||||
// capture message calls.
|
|
||||||
AttachStacktrace bool
|
|
||||||
// The sample rate for event submission in the range [0.0, 1.0]. By default,
|
|
||||||
// all events are sent. Thus, as a historical special case, the sample rate
|
|
||||||
// 0.0 is treated as if it was 1.0. To drop all events, set the DSN to the
|
|
||||||
// empty string.
|
|
||||||
SampleRate float64
|
|
||||||
// Enable performance tracing.
|
|
||||||
EnableTracing bool
|
|
||||||
// The sample rate for sampling traces in the range [0.0, 1.0].
|
|
||||||
TracesSampleRate float64
|
|
||||||
// Used to customize the sampling of traces, overrides TracesSampleRate.
|
|
||||||
TracesSampler TracesSampler
|
|
||||||
// List of regexp strings that will be used to match against event's message
|
|
||||||
// and if applicable, caught errors type and value.
|
|
||||||
// If the match is found, then a whole event will be dropped.
|
|
||||||
IgnoreErrors []string
|
|
||||||
// List of regexp strings that will be used to match against a transaction's
|
|
||||||
// name. If a match is found, then the transaction will be dropped.
|
|
||||||
IgnoreTransactions []string
|
|
||||||
// If this flag is enabled, certain personally identifiable information (PII) is added by active integrations.
|
|
||||||
// By default, no such data is sent.
|
|
||||||
SendDefaultPII bool
|
|
||||||
// BeforeSend is called before error events are sent to Sentry.
|
|
||||||
// Use it to mutate the event or return nil to discard the event.
|
|
||||||
BeforeSend func(event *Event, hint *EventHint) *Event
|
|
||||||
// BeforeSendTransaction is called before transaction events are sent to Sentry.
|
|
||||||
// Use it to mutate the transaction or return nil to discard the transaction.
|
|
||||||
BeforeSendTransaction func(event *Event, hint *EventHint) *Event
|
|
||||||
// Before breadcrumb add callback.
|
|
||||||
BeforeBreadcrumb func(breadcrumb *Breadcrumb, hint *BreadcrumbHint) *Breadcrumb
|
|
||||||
// Integrations to be installed on the current Client, receives default
|
|
||||||
// integrations.
|
|
||||||
Integrations func([]Integration) []Integration
|
|
||||||
// io.Writer implementation that should be used with the Debug mode.
|
|
||||||
DebugWriter io.Writer
|
|
||||||
// The transport to use. Defaults to HTTPTransport.
|
|
||||||
Transport Transport
|
|
||||||
// The server name to be reported.
|
|
||||||
ServerName string
|
|
||||||
// The release to be sent with events.
|
|
||||||
//
|
|
||||||
// Some Sentry features are built around releases, and, thus, reporting
|
|
||||||
// events with a non-empty release improves the product experience. See
|
|
||||||
// https://docs.sentry.io/product/releases/.
|
|
||||||
//
|
|
||||||
// If Release is not set, the SDK will try to derive a default value
|
|
||||||
// from environment variables or the Git repository in the working
|
|
||||||
// directory.
|
|
||||||
//
|
|
||||||
// If you distribute a compiled binary, it is recommended to set the
|
|
||||||
// Release value explicitly at build time. As an example, you can use:
|
|
||||||
//
|
|
||||||
// go build -ldflags='-X main.release=VALUE'
|
|
||||||
//
|
|
||||||
// That will set the value of a predeclared variable 'release' in the
|
|
||||||
// 'main' package to 'VALUE'. Then, use that variable when initializing
|
|
||||||
// the SDK:
|
|
||||||
//
|
|
||||||
// sentry.Init(ClientOptions{Release: release})
|
|
||||||
//
|
|
||||||
// See https://golang.org/cmd/go/ and https://golang.org/cmd/link/ for
|
|
||||||
// the official documentation of -ldflags and -X, respectively.
|
|
||||||
Release string
|
|
||||||
// The dist to be sent with events.
|
|
||||||
Dist string
|
|
||||||
// The environment to be sent with events.
|
|
||||||
Environment string
|
|
||||||
// Maximum number of breadcrumbs
|
|
||||||
// when MaxBreadcrumbs is negative then ignore breadcrumbs.
|
|
||||||
MaxBreadcrumbs int
|
|
||||||
// Maximum number of spans.
|
|
||||||
//
|
|
||||||
// See https://develop.sentry.dev/sdk/envelopes/#size-limits for size limits
|
|
||||||
// applied during event ingestion. Events that exceed these limits might get dropped.
|
|
||||||
MaxSpans int
|
|
||||||
// An optional pointer to http.Client that will be used with a default
|
|
||||||
// HTTPTransport. Using your own client will make HTTPTransport, HTTPProxy,
|
|
||||||
// HTTPSProxy and CaCerts options ignored.
|
|
||||||
HTTPClient *http.Client
|
|
||||||
// An optional pointer to http.Transport that will be used with a default
|
|
||||||
// HTTPTransport. Using your own transport will make HTTPProxy, HTTPSProxy
|
|
||||||
// and CaCerts options ignored.
|
|
||||||
HTTPTransport http.RoundTripper
|
|
||||||
// An optional HTTP proxy to use.
|
|
||||||
// This will default to the HTTP_PROXY environment variable.
|
|
||||||
HTTPProxy string
|
|
||||||
// An optional HTTPS proxy to use.
|
|
||||||
// This will default to the HTTPS_PROXY environment variable.
|
|
||||||
// HTTPS_PROXY takes precedence over HTTP_PROXY for https requests.
|
|
||||||
HTTPSProxy string
|
|
||||||
// An optional set of SSL certificates to use.
|
|
||||||
CaCerts *x509.CertPool
|
|
||||||
// MaxErrorDepth is the maximum number of errors reported in a chain of errors.
|
|
||||||
// This protects the SDK from an arbitrarily long chain of wrapped errors.
|
|
||||||
//
|
|
||||||
// An additional consideration is that arguably reporting a long chain of errors
|
|
||||||
// is of little use when debugging production errors with Sentry. The Sentry UI
|
|
||||||
// is not optimized for long chains either. The top-level error together with a
|
|
||||||
// stack trace is often the most useful information.
|
|
||||||
MaxErrorDepth int
|
|
||||||
// Default event tags. These are overridden by tags set on a scope.
|
|
||||||
Tags map[string]string
|
|
||||||
}
|
|
||||||
|
|
||||||
// Client is the underlying processor that is used by the main API and Hub
|
|
||||||
// instances. It must be created with NewClient.
|
|
||||||
type Client struct {
|
|
||||||
mu sync.RWMutex
|
|
||||||
options ClientOptions
|
|
||||||
dsn *Dsn
|
|
||||||
eventProcessors []EventProcessor
|
|
||||||
integrations []Integration
|
|
||||||
sdkIdentifier string
|
|
||||||
sdkVersion string
|
|
||||||
// Transport is read-only. Replacing the transport of an existing client is
|
|
||||||
// not supported, create a new client instead.
|
|
||||||
Transport Transport
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewClient creates and returns an instance of Client configured using
|
|
||||||
// ClientOptions.
|
|
||||||
//
|
|
||||||
// Most users will not create clients directly. Instead, initialize the SDK with
|
|
||||||
// Init and use the package-level functions (for simple programs that run on a
|
|
||||||
// single goroutine) or hub methods (for concurrent programs, for example web
|
|
||||||
// servers).
|
|
||||||
func NewClient(options ClientOptions) (*Client, error) {
|
|
||||||
// The default error event sample rate for all SDKs is 1.0 (send all).
|
|
||||||
//
|
|
||||||
// In Go, the zero value (default) for float64 is 0.0, which means that
|
|
||||||
// constructing a client with NewClient(ClientOptions{}), or, equivalently,
|
|
||||||
// initializing the SDK with Init(ClientOptions{}) without an explicit
|
|
||||||
// SampleRate would drop all events.
|
|
||||||
//
|
|
||||||
// To retain the desired default behavior, we exceptionally flip SampleRate
|
|
||||||
// from 0.0 to 1.0 here. Setting the sample rate to 0.0 is not very useful
|
|
||||||
// anyway, and the same end result can be achieved in many other ways like
|
|
||||||
// not initializing the SDK, setting the DSN to the empty string or using an
|
|
||||||
// event processor that always returns nil.
|
|
||||||
//
|
|
||||||
// An alternative API could be such that default options don't need to be
|
|
||||||
// the same as Go's zero values, for example using the Functional Options
|
|
||||||
// pattern. That would either require a breaking change if we want to reuse
|
|
||||||
// the obvious NewClient name, or a new function as an alternative
|
|
||||||
// constructor.
|
|
||||||
if options.SampleRate == 0.0 {
|
|
||||||
options.SampleRate = 1.0
|
|
||||||
}
|
|
||||||
|
|
||||||
if options.Debug {
|
|
||||||
debugWriter := options.DebugWriter
|
|
||||||
if debugWriter == nil {
|
|
||||||
debugWriter = os.Stderr
|
|
||||||
}
|
|
||||||
Logger.SetOutput(debugWriter)
|
|
||||||
}
|
|
||||||
|
|
||||||
if options.Dsn == "" {
|
|
||||||
options.Dsn = os.Getenv("SENTRY_DSN")
|
|
||||||
}
|
|
||||||
|
|
||||||
if options.Release == "" {
|
|
||||||
options.Release = defaultRelease()
|
|
||||||
}
|
|
||||||
|
|
||||||
if options.Environment == "" {
|
|
||||||
options.Environment = os.Getenv("SENTRY_ENVIRONMENT")
|
|
||||||
}
|
|
||||||
|
|
||||||
if options.MaxErrorDepth == 0 {
|
|
||||||
options.MaxErrorDepth = maxErrorDepth
|
|
||||||
}
|
|
||||||
|
|
||||||
if options.MaxSpans == 0 {
|
|
||||||
options.MaxSpans = defaultMaxSpans
|
|
||||||
}
|
|
||||||
|
|
||||||
// SENTRYGODEBUG is a comma-separated list of key=value pairs (similar
|
|
||||||
// to GODEBUG). It is not a supported feature: recognized debug options
|
|
||||||
// may change any time.
|
|
||||||
//
|
|
||||||
// The intended public is SDK developers. It is orthogonal to
|
|
||||||
// options.Debug, which is also available for SDK users.
|
|
||||||
dbg := strings.Split(os.Getenv("SENTRYGODEBUG"), ",")
|
|
||||||
sort.Strings(dbg)
|
|
||||||
// dbgOpt returns true when the given debug option is enabled, for
|
|
||||||
// example SENTRYGODEBUG=someopt=1.
|
|
||||||
dbgOpt := func(opt string) bool {
|
|
||||||
s := opt + "=1"
|
|
||||||
return dbg[sort.SearchStrings(dbg, s)%len(dbg)] == s
|
|
||||||
}
|
|
||||||
if dbgOpt("httpdump") || dbgOpt("httptrace") {
|
|
||||||
options.HTTPTransport = &debug.Transport{
|
|
||||||
RoundTripper: http.DefaultTransport,
|
|
||||||
Output: os.Stderr,
|
|
||||||
Dump: dbgOpt("httpdump"),
|
|
||||||
Trace: dbgOpt("httptrace"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
var dsn *Dsn
|
|
||||||
if options.Dsn != "" {
|
|
||||||
var err error
|
|
||||||
dsn, err = NewDsn(options.Dsn)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
client := Client{
|
|
||||||
options: options,
|
|
||||||
dsn: dsn,
|
|
||||||
sdkIdentifier: sdkIdentifier,
|
|
||||||
sdkVersion: SDKVersion,
|
|
||||||
}
|
|
||||||
|
|
||||||
client.setupTransport()
|
|
||||||
client.setupIntegrations()
|
|
||||||
|
|
||||||
return &client, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (client *Client) setupTransport() {
|
|
||||||
opts := client.options
|
|
||||||
transport := opts.Transport
|
|
||||||
|
|
||||||
if transport == nil {
|
|
||||||
if opts.Dsn == "" {
|
|
||||||
transport = new(noopTransport)
|
|
||||||
} else {
|
|
||||||
httpTransport := NewHTTPTransport()
|
|
||||||
// When tracing is enabled, use larger buffer to
|
|
||||||
// accommodate more concurrent events.
|
|
||||||
// TODO(tracing): consider using separate buffers per
|
|
||||||
// event type.
|
|
||||||
if opts.EnableTracing {
|
|
||||||
httpTransport.BufferSize = 1000
|
|
||||||
}
|
|
||||||
transport = httpTransport
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
transport.Configure(opts)
|
|
||||||
client.Transport = transport
|
|
||||||
}
|
|
||||||
|
|
||||||
func (client *Client) setupIntegrations() {
|
|
||||||
integrations := []Integration{
|
|
||||||
new(contextifyFramesIntegration),
|
|
||||||
new(environmentIntegration),
|
|
||||||
new(modulesIntegration),
|
|
||||||
new(ignoreErrorsIntegration),
|
|
||||||
new(ignoreTransactionsIntegration),
|
|
||||||
new(globalTagsIntegration),
|
|
||||||
}
|
|
||||||
|
|
||||||
if client.options.Integrations != nil {
|
|
||||||
integrations = client.options.Integrations(integrations)
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, integration := range integrations {
|
|
||||||
if client.integrationAlreadyInstalled(integration.Name()) {
|
|
||||||
Logger.Printf("Integration %s is already installed\n", integration.Name())
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
client.integrations = append(client.integrations, integration)
|
|
||||||
integration.SetupOnce(client)
|
|
||||||
Logger.Printf("Integration installed: %s\n", integration.Name())
|
|
||||||
}
|
|
||||||
|
|
||||||
sort.Slice(client.integrations, func(i, j int) bool {
|
|
||||||
return client.integrations[i].Name() < client.integrations[j].Name()
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// AddEventProcessor adds an event processor to the client. It must not be
|
|
||||||
// called from concurrent goroutines. Most users will prefer to use
|
|
||||||
// ClientOptions.BeforeSend or Scope.AddEventProcessor instead.
|
|
||||||
//
|
|
||||||
// Note that typical programs have only a single client created by Init and the
|
|
||||||
// client is shared among multiple hubs, one per goroutine, such that adding an
|
|
||||||
// event processor to the client affects all hubs that share the client.
|
|
||||||
func (client *Client) AddEventProcessor(processor EventProcessor) {
|
|
||||||
client.eventProcessors = append(client.eventProcessors, processor)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Options return ClientOptions for the current Client.
|
|
||||||
func (client *Client) Options() ClientOptions {
|
|
||||||
// Note: internally, consider using `client.options` instead of `client.Options()` to avoid copying the object each time.
|
|
||||||
return client.options
|
|
||||||
}
|
|
||||||
|
|
||||||
// CaptureMessage captures an arbitrary message.
|
|
||||||
func (client *Client) CaptureMessage(message string, hint *EventHint, scope EventModifier) *EventID {
|
|
||||||
event := client.EventFromMessage(message, LevelInfo)
|
|
||||||
return client.CaptureEvent(event, hint, scope)
|
|
||||||
}
|
|
||||||
|
|
||||||
// CaptureException captures an error.
|
|
||||||
func (client *Client) CaptureException(exception error, hint *EventHint, scope EventModifier) *EventID {
|
|
||||||
event := client.EventFromException(exception, LevelError)
|
|
||||||
return client.CaptureEvent(event, hint, scope)
|
|
||||||
}
|
|
||||||
|
|
||||||
// CaptureCheckIn captures a check in.
|
|
||||||
func (client *Client) CaptureCheckIn(checkIn *CheckIn, monitorConfig *MonitorConfig, scope EventModifier) *EventID {
|
|
||||||
event := client.EventFromCheckIn(checkIn, monitorConfig)
|
|
||||||
if event != nil && event.CheckIn != nil {
|
|
||||||
client.CaptureEvent(event, nil, scope)
|
|
||||||
return &event.CheckIn.ID
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// CaptureEvent captures an event on the currently active client if any.
|
|
||||||
//
|
|
||||||
// The event must already be assembled. Typically code would instead use
|
|
||||||
// the utility methods like CaptureException. The return value is the
|
|
||||||
// event ID. In case Sentry is disabled or event was dropped, the return value will be nil.
|
|
||||||
func (client *Client) CaptureEvent(event *Event, hint *EventHint, scope EventModifier) *EventID {
|
|
||||||
return client.processEvent(event, hint, scope)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Recover captures a panic.
|
|
||||||
// Returns EventID if successfully, or nil if there's no error to recover from.
|
|
||||||
func (client *Client) Recover(err interface{}, hint *EventHint, scope EventModifier) *EventID {
|
|
||||||
if err == nil {
|
|
||||||
err = recover()
|
|
||||||
}
|
|
||||||
|
|
||||||
// Normally we would not pass a nil Context, but RecoverWithContext doesn't
|
|
||||||
// use the Context for communicating deadline nor cancelation. All it does
|
|
||||||
// is store the Context in the EventHint and there nil means the Context is
|
|
||||||
// not available.
|
|
||||||
// nolint: staticcheck
|
|
||||||
return client.RecoverWithContext(nil, err, hint, scope)
|
|
||||||
}
|
|
||||||
|
|
||||||
// RecoverWithContext captures a panic and passes relevant context object.
|
|
||||||
// Returns EventID if successfully, or nil if there's no error to recover from.
|
|
||||||
func (client *Client) RecoverWithContext(
|
|
||||||
ctx context.Context,
|
|
||||||
err interface{},
|
|
||||||
hint *EventHint,
|
|
||||||
scope EventModifier,
|
|
||||||
) *EventID {
|
|
||||||
if err == nil {
|
|
||||||
err = recover()
|
|
||||||
}
|
|
||||||
if err == nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
if ctx != nil {
|
|
||||||
if hint == nil {
|
|
||||||
hint = &EventHint{}
|
|
||||||
}
|
|
||||||
if hint.Context == nil {
|
|
||||||
hint.Context = ctx
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
var event *Event
|
|
||||||
switch err := err.(type) {
|
|
||||||
case error:
|
|
||||||
event = client.EventFromException(err, LevelFatal)
|
|
||||||
case string:
|
|
||||||
event = client.EventFromMessage(err, LevelFatal)
|
|
||||||
default:
|
|
||||||
event = client.EventFromMessage(fmt.Sprintf("%#v", err), LevelFatal)
|
|
||||||
}
|
|
||||||
return client.CaptureEvent(event, hint, scope)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Flush waits until the underlying Transport sends any buffered events to the
|
|
||||||
// Sentry server, blocking for at most the given timeout. It returns false if
|
|
||||||
// the timeout was reached. In that case, some events may not have been sent.
|
|
||||||
//
|
|
||||||
// Flush should be called before terminating the program to avoid
|
|
||||||
// unintentionally dropping events.
|
|
||||||
//
|
|
||||||
// Do not call Flush indiscriminately after every call to CaptureEvent,
|
|
||||||
// CaptureException or CaptureMessage. Instead, to have the SDK send events over
|
|
||||||
// the network synchronously, configure it to use the HTTPSyncTransport in the
|
|
||||||
// call to Init.
|
|
||||||
func (client *Client) Flush(timeout time.Duration) bool {
|
|
||||||
return client.Transport.Flush(timeout)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Close clean up underlying Transport resources.
|
|
||||||
//
|
|
||||||
// Close should be called after Flush and before terminating the program
|
|
||||||
// otherwise some events may be lost.
|
|
||||||
func (client *Client) Close() {
|
|
||||||
client.Transport.Close()
|
|
||||||
}
|
|
||||||
|
|
||||||
// EventFromMessage creates an event from the given message string.
|
|
||||||
func (client *Client) EventFromMessage(message string, level Level) *Event {
|
|
||||||
if message == "" {
|
|
||||||
err := usageError{fmt.Errorf("%s called with empty message", callerFunctionName())}
|
|
||||||
return client.EventFromException(err, level)
|
|
||||||
}
|
|
||||||
event := NewEvent()
|
|
||||||
event.Level = level
|
|
||||||
event.Message = message
|
|
||||||
|
|
||||||
if client.options.AttachStacktrace {
|
|
||||||
event.Threads = []Thread{{
|
|
||||||
Stacktrace: NewStacktrace(),
|
|
||||||
Crashed: false,
|
|
||||||
Current: true,
|
|
||||||
}}
|
|
||||||
}
|
|
||||||
|
|
||||||
return event
|
|
||||||
}
|
|
||||||
|
|
||||||
// EventFromException creates a new Sentry event from the given `error` instance.
|
|
||||||
func (client *Client) EventFromException(exception error, level Level) *Event {
|
|
||||||
event := NewEvent()
|
|
||||||
event.Level = level
|
|
||||||
|
|
||||||
err := exception
|
|
||||||
if err == nil {
|
|
||||||
err = usageError{fmt.Errorf("%s called with nil error", callerFunctionName())}
|
|
||||||
}
|
|
||||||
|
|
||||||
event.SetException(err, client.options.MaxErrorDepth)
|
|
||||||
|
|
||||||
return event
|
|
||||||
}
|
|
||||||
|
|
||||||
// EventFromCheckIn creates a new Sentry event from the given `check_in` instance.
|
|
||||||
func (client *Client) EventFromCheckIn(checkIn *CheckIn, monitorConfig *MonitorConfig) *Event {
|
|
||||||
if checkIn == nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
event := NewEvent()
|
|
||||||
event.Type = checkInType
|
|
||||||
|
|
||||||
var checkInID EventID
|
|
||||||
if checkIn.ID == "" {
|
|
||||||
checkInID = EventID(uuid())
|
|
||||||
} else {
|
|
||||||
checkInID = checkIn.ID
|
|
||||||
}
|
|
||||||
|
|
||||||
event.CheckIn = &CheckIn{
|
|
||||||
ID: checkInID,
|
|
||||||
MonitorSlug: checkIn.MonitorSlug,
|
|
||||||
Status: checkIn.Status,
|
|
||||||
Duration: checkIn.Duration,
|
|
||||||
}
|
|
||||||
event.MonitorConfig = monitorConfig
|
|
||||||
|
|
||||||
return event
|
|
||||||
}
|
|
||||||
|
|
||||||
func (client *Client) SetSDKIdentifier(identifier string) {
|
|
||||||
client.mu.Lock()
|
|
||||||
defer client.mu.Unlock()
|
|
||||||
|
|
||||||
client.sdkIdentifier = identifier
|
|
||||||
}
|
|
||||||
|
|
||||||
func (client *Client) GetSDKIdentifier() string {
|
|
||||||
client.mu.RLock()
|
|
||||||
defer client.mu.RUnlock()
|
|
||||||
|
|
||||||
return client.sdkIdentifier
|
|
||||||
}
|
|
||||||
|
|
||||||
func (client *Client) processEvent(event *Event, hint *EventHint, scope EventModifier) *EventID {
|
|
||||||
if event == nil {
|
|
||||||
err := usageError{fmt.Errorf("%s called with nil event", callerFunctionName())}
|
|
||||||
return client.CaptureException(err, hint, scope)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Transactions are sampled by options.TracesSampleRate or
|
|
||||||
// options.TracesSampler when they are started. Other events
|
|
||||||
// (errors, messages) are sampled here. Does not apply to check-ins.
|
|
||||||
if event.Type != transactionType && event.Type != checkInType && !sample(client.options.SampleRate) {
|
|
||||||
Logger.Println("Event dropped due to SampleRate hit.")
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
if event = client.prepareEvent(event, hint, scope); event == nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Apply beforeSend* processors
|
|
||||||
if hint == nil {
|
|
||||||
hint = &EventHint{}
|
|
||||||
}
|
|
||||||
if event.Type == transactionType && client.options.BeforeSendTransaction != nil {
|
|
||||||
// Transaction events
|
|
||||||
if event = client.options.BeforeSendTransaction(event, hint); event == nil {
|
|
||||||
Logger.Println("Transaction dropped due to BeforeSendTransaction callback.")
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
} else if event.Type != transactionType && event.Type != checkInType && client.options.BeforeSend != nil {
|
|
||||||
// All other events
|
|
||||||
if event = client.options.BeforeSend(event, hint); event == nil {
|
|
||||||
Logger.Println("Event dropped due to BeforeSend callback.")
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
client.Transport.SendEvent(event)
|
|
||||||
|
|
||||||
return &event.EventID
|
|
||||||
}
|
|
||||||
|
|
||||||
func (client *Client) prepareEvent(event *Event, hint *EventHint, scope EventModifier) *Event {
|
|
||||||
if event.EventID == "" {
|
|
||||||
// TODO set EventID when the event is created, same as in other SDKs. It's necessary for profileTransaction.ID.
|
|
||||||
event.EventID = EventID(uuid())
|
|
||||||
}
|
|
||||||
|
|
||||||
if event.Timestamp.IsZero() {
|
|
||||||
event.Timestamp = time.Now()
|
|
||||||
}
|
|
||||||
|
|
||||||
if event.Level == "" {
|
|
||||||
event.Level = LevelInfo
|
|
||||||
}
|
|
||||||
|
|
||||||
if event.ServerName == "" {
|
|
||||||
event.ServerName = client.options.ServerName
|
|
||||||
|
|
||||||
if event.ServerName == "" {
|
|
||||||
event.ServerName = hostname
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if event.Release == "" {
|
|
||||||
event.Release = client.options.Release
|
|
||||||
}
|
|
||||||
|
|
||||||
if event.Dist == "" {
|
|
||||||
event.Dist = client.options.Dist
|
|
||||||
}
|
|
||||||
|
|
||||||
if event.Environment == "" {
|
|
||||||
event.Environment = client.options.Environment
|
|
||||||
}
|
|
||||||
|
|
||||||
event.Platform = "go"
|
|
||||||
event.Sdk = SdkInfo{
|
|
||||||
Name: client.GetSDKIdentifier(),
|
|
||||||
Version: SDKVersion,
|
|
||||||
Integrations: client.listIntegrations(),
|
|
||||||
Packages: []SdkPackage{{
|
|
||||||
Name: "sentry-go",
|
|
||||||
Version: SDKVersion,
|
|
||||||
}},
|
|
||||||
}
|
|
||||||
|
|
||||||
if scope != nil {
|
|
||||||
event = scope.ApplyToEvent(event, hint, client)
|
|
||||||
if event == nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, processor := range client.eventProcessors {
|
|
||||||
id := event.EventID
|
|
||||||
event = processor(event, hint)
|
|
||||||
if event == nil {
|
|
||||||
Logger.Printf("Event dropped by one of the Client EventProcessors: %s\n", id)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, processor := range globalEventProcessors {
|
|
||||||
id := event.EventID
|
|
||||||
event = processor(event, hint)
|
|
||||||
if event == nil {
|
|
||||||
Logger.Printf("Event dropped by one of the Global EventProcessors: %s\n", id)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return event
|
|
||||||
}
|
|
||||||
|
|
||||||
func (client *Client) listIntegrations() []string {
|
|
||||||
integrations := make([]string, len(client.integrations))
|
|
||||||
for i, integration := range client.integrations {
|
|
||||||
integrations[i] = integration.Name()
|
|
||||||
}
|
|
||||||
return integrations
|
|
||||||
}
|
|
||||||
|
|
||||||
func (client *Client) integrationAlreadyInstalled(name string) bool {
|
|
||||||
for _, integration := range client.integrations {
|
|
||||||
if integration.Name() == name {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
// sample returns true with the given probability, which must be in the range
|
|
||||||
// [0.0, 1.0].
|
|
||||||
func sample(probability float64) bool {
|
|
||||||
return rng.Float64() < probability
|
|
||||||
}
|
|
||||||
-6
@@ -1,6 +0,0 @@
|
|||||||
/*
|
|
||||||
Package repository: https://github.com/getsentry/sentry-go/
|
|
||||||
|
|
||||||
For more information about Sentry and SDK features, please have a look at the official documentation site: https://docs.sentry.io/platforms/go/
|
|
||||||
*/
|
|
||||||
package sentry
|
|
||||||
-233
@@ -1,233 +0,0 @@
|
|||||||
package sentry
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
"net/url"
|
|
||||||
"strconv"
|
|
||||||
"strings"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
type scheme string
|
|
||||||
|
|
||||||
const (
|
|
||||||
schemeHTTP scheme = "http"
|
|
||||||
schemeHTTPS scheme = "https"
|
|
||||||
)
|
|
||||||
|
|
||||||
func (scheme scheme) defaultPort() int {
|
|
||||||
switch scheme {
|
|
||||||
case schemeHTTPS:
|
|
||||||
return 443
|
|
||||||
case schemeHTTP:
|
|
||||||
return 80
|
|
||||||
default:
|
|
||||||
return 80
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// DsnParseError represents an error that occurs if a Sentry
|
|
||||||
// DSN cannot be parsed.
|
|
||||||
type DsnParseError struct {
|
|
||||||
Message string
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e DsnParseError) Error() string {
|
|
||||||
return "[Sentry] DsnParseError: " + e.Message
|
|
||||||
}
|
|
||||||
|
|
||||||
// Dsn is used as the remote address source to client transport.
|
|
||||||
type Dsn struct {
|
|
||||||
scheme scheme
|
|
||||||
publicKey string
|
|
||||||
secretKey string
|
|
||||||
host string
|
|
||||||
port int
|
|
||||||
path string
|
|
||||||
projectID string
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewDsn creates a Dsn by parsing rawURL. Most users will never call this
|
|
||||||
// function directly. It is provided for use in custom Transport
|
|
||||||
// implementations.
|
|
||||||
func NewDsn(rawURL string) (*Dsn, error) {
|
|
||||||
// Parse
|
|
||||||
parsedURL, err := url.Parse(rawURL)
|
|
||||||
if err != nil {
|
|
||||||
return nil, &DsnParseError{fmt.Sprintf("invalid url: %v", err)}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Scheme
|
|
||||||
var scheme scheme
|
|
||||||
switch parsedURL.Scheme {
|
|
||||||
case "http":
|
|
||||||
scheme = schemeHTTP
|
|
||||||
case "https":
|
|
||||||
scheme = schemeHTTPS
|
|
||||||
default:
|
|
||||||
return nil, &DsnParseError{"invalid scheme"}
|
|
||||||
}
|
|
||||||
|
|
||||||
// PublicKey
|
|
||||||
publicKey := parsedURL.User.Username()
|
|
||||||
if publicKey == "" {
|
|
||||||
return nil, &DsnParseError{"empty username"}
|
|
||||||
}
|
|
||||||
|
|
||||||
// SecretKey
|
|
||||||
var secretKey string
|
|
||||||
if parsedSecretKey, ok := parsedURL.User.Password(); ok {
|
|
||||||
secretKey = parsedSecretKey
|
|
||||||
}
|
|
||||||
|
|
||||||
// Host
|
|
||||||
host := parsedURL.Hostname()
|
|
||||||
if host == "" {
|
|
||||||
return nil, &DsnParseError{"empty host"}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Port
|
|
||||||
var port int
|
|
||||||
if p := parsedURL.Port(); p != "" {
|
|
||||||
port, err = strconv.Atoi(p)
|
|
||||||
if err != nil {
|
|
||||||
return nil, &DsnParseError{"invalid port"}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
port = scheme.defaultPort()
|
|
||||||
}
|
|
||||||
|
|
||||||
// ProjectID
|
|
||||||
if parsedURL.Path == "" || parsedURL.Path == "/" {
|
|
||||||
return nil, &DsnParseError{"empty project id"}
|
|
||||||
}
|
|
||||||
pathSegments := strings.Split(parsedURL.Path[1:], "/")
|
|
||||||
projectID := pathSegments[len(pathSegments)-1]
|
|
||||||
|
|
||||||
if projectID == "" {
|
|
||||||
return nil, &DsnParseError{"empty project id"}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Path
|
|
||||||
var path string
|
|
||||||
if len(pathSegments) > 1 {
|
|
||||||
path = "/" + strings.Join(pathSegments[0:len(pathSegments)-1], "/")
|
|
||||||
}
|
|
||||||
|
|
||||||
return &Dsn{
|
|
||||||
scheme: scheme,
|
|
||||||
publicKey: publicKey,
|
|
||||||
secretKey: secretKey,
|
|
||||||
host: host,
|
|
||||||
port: port,
|
|
||||||
path: path,
|
|
||||||
projectID: projectID,
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// String formats Dsn struct into a valid string url.
|
|
||||||
func (dsn Dsn) String() string {
|
|
||||||
var url string
|
|
||||||
url += fmt.Sprintf("%s://%s", dsn.scheme, dsn.publicKey)
|
|
||||||
if dsn.secretKey != "" {
|
|
||||||
url += fmt.Sprintf(":%s", dsn.secretKey)
|
|
||||||
}
|
|
||||||
url += fmt.Sprintf("@%s", dsn.host)
|
|
||||||
if dsn.port != dsn.scheme.defaultPort() {
|
|
||||||
url += fmt.Sprintf(":%d", dsn.port)
|
|
||||||
}
|
|
||||||
if dsn.path != "" {
|
|
||||||
url += dsn.path
|
|
||||||
}
|
|
||||||
url += fmt.Sprintf("/%s", dsn.projectID)
|
|
||||||
return url
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get the scheme of the DSN.
|
|
||||||
func (dsn Dsn) GetScheme() string {
|
|
||||||
return string(dsn.scheme)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get the public key of the DSN.
|
|
||||||
func (dsn Dsn) GetPublicKey() string {
|
|
||||||
return dsn.publicKey
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get the secret key of the DSN.
|
|
||||||
func (dsn Dsn) GetSecretKey() string {
|
|
||||||
return dsn.secretKey
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get the host of the DSN.
|
|
||||||
func (dsn Dsn) GetHost() string {
|
|
||||||
return dsn.host
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get the port of the DSN.
|
|
||||||
func (dsn Dsn) GetPort() int {
|
|
||||||
return dsn.port
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get the path of the DSN.
|
|
||||||
func (dsn Dsn) GetPath() string {
|
|
||||||
return dsn.path
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get the project ID of the DSN.
|
|
||||||
func (dsn Dsn) GetProjectID() string {
|
|
||||||
return dsn.projectID
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetAPIURL returns the URL of the envelope endpoint of the project
|
|
||||||
// associated with the DSN.
|
|
||||||
func (dsn Dsn) GetAPIURL() *url.URL {
|
|
||||||
var rawURL string
|
|
||||||
rawURL += fmt.Sprintf("%s://%s", dsn.scheme, dsn.host)
|
|
||||||
if dsn.port != dsn.scheme.defaultPort() {
|
|
||||||
rawURL += fmt.Sprintf(":%d", dsn.port)
|
|
||||||
}
|
|
||||||
if dsn.path != "" {
|
|
||||||
rawURL += dsn.path
|
|
||||||
}
|
|
||||||
rawURL += fmt.Sprintf("/api/%s/%s/", dsn.projectID, "envelope")
|
|
||||||
parsedURL, _ := url.Parse(rawURL)
|
|
||||||
return parsedURL
|
|
||||||
}
|
|
||||||
|
|
||||||
// RequestHeaders returns all the necessary headers that have to be used in the transport when seinding events
|
|
||||||
// to the /store endpoint.
|
|
||||||
//
|
|
||||||
// Deprecated: This method shall only be used if you want to implement your own transport that sends events to
|
|
||||||
// the /store endpoint. If you're using the transport provided by the SDK, all necessary headers to authenticate
|
|
||||||
// against the /envelope endpoint are added automatically.
|
|
||||||
func (dsn Dsn) RequestHeaders() map[string]string {
|
|
||||||
auth := fmt.Sprintf("Sentry sentry_version=%s, sentry_timestamp=%d, "+
|
|
||||||
"sentry_client=sentry.go/%s, sentry_key=%s", apiVersion, time.Now().Unix(), SDKVersion, dsn.publicKey)
|
|
||||||
|
|
||||||
if dsn.secretKey != "" {
|
|
||||||
auth = fmt.Sprintf("%s, sentry_secret=%s", auth, dsn.secretKey)
|
|
||||||
}
|
|
||||||
|
|
||||||
return map[string]string{
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
"X-Sentry-Auth": auth,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// MarshalJSON converts the Dsn struct to JSON.
|
|
||||||
func (dsn Dsn) MarshalJSON() ([]byte, error) {
|
|
||||||
return json.Marshal(dsn.String())
|
|
||||||
}
|
|
||||||
|
|
||||||
// UnmarshalJSON converts JSON data to the Dsn struct.
|
|
||||||
func (dsn *Dsn) UnmarshalJSON(data []byte) error {
|
|
||||||
var str string
|
|
||||||
_ = json.Unmarshal(data, &str)
|
|
||||||
newDsn, err := NewDsn(str)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
*dsn = *newDsn
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
-154
@@ -1,154 +0,0 @@
|
|||||||
package sentry
|
|
||||||
|
|
||||||
import (
|
|
||||||
"strconv"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"github.com/getsentry/sentry-go/internal/otel/baggage"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
sentryPrefix = "sentry-"
|
|
||||||
)
|
|
||||||
|
|
||||||
// DynamicSamplingContext holds information about the current event that can be used to make dynamic sampling decisions.
|
|
||||||
type DynamicSamplingContext struct {
|
|
||||||
Entries map[string]string
|
|
||||||
Frozen bool
|
|
||||||
}
|
|
||||||
|
|
||||||
func DynamicSamplingContextFromHeader(header []byte) (DynamicSamplingContext, error) {
|
|
||||||
bag, err := baggage.Parse(string(header))
|
|
||||||
if err != nil {
|
|
||||||
return DynamicSamplingContext{}, err
|
|
||||||
}
|
|
||||||
|
|
||||||
entries := map[string]string{}
|
|
||||||
for _, member := range bag.Members() {
|
|
||||||
// We only store baggage members if their key starts with "sentry-".
|
|
||||||
if k, v := member.Key(), member.Value(); strings.HasPrefix(k, sentryPrefix) {
|
|
||||||
entries[strings.TrimPrefix(k, sentryPrefix)] = v
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return DynamicSamplingContext{
|
|
||||||
Entries: entries,
|
|
||||||
// If there's at least one Sentry value, we consider the DSC frozen
|
|
||||||
Frozen: len(entries) > 0,
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func DynamicSamplingContextFromTransaction(span *Span) DynamicSamplingContext {
|
|
||||||
hub := hubFromContext(span.Context())
|
|
||||||
scope := hub.Scope()
|
|
||||||
client := hub.Client()
|
|
||||||
|
|
||||||
if client == nil || scope == nil {
|
|
||||||
return DynamicSamplingContext{
|
|
||||||
Entries: map[string]string{},
|
|
||||||
Frozen: false,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
entries := make(map[string]string)
|
|
||||||
|
|
||||||
if traceID := span.TraceID.String(); traceID != "" {
|
|
||||||
entries["trace_id"] = traceID
|
|
||||||
}
|
|
||||||
if sampleRate := span.sampleRate; sampleRate != 0 {
|
|
||||||
entries["sample_rate"] = strconv.FormatFloat(sampleRate, 'f', -1, 64)
|
|
||||||
}
|
|
||||||
|
|
||||||
if dsn := client.dsn; dsn != nil {
|
|
||||||
if publicKey := dsn.publicKey; publicKey != "" {
|
|
||||||
entries["public_key"] = publicKey
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if release := client.options.Release; release != "" {
|
|
||||||
entries["release"] = release
|
|
||||||
}
|
|
||||||
if environment := client.options.Environment; environment != "" {
|
|
||||||
entries["environment"] = environment
|
|
||||||
}
|
|
||||||
|
|
||||||
// Only include the transaction name if it's of good quality (not empty and not SourceURL)
|
|
||||||
if span.Source != "" && span.Source != SourceURL {
|
|
||||||
if span.IsTransaction() {
|
|
||||||
entries["transaction"] = span.Name
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
entries["sampled"] = strconv.FormatBool(span.Sampled.Bool())
|
|
||||||
|
|
||||||
return DynamicSamplingContext{Entries: entries, Frozen: true}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (d DynamicSamplingContext) HasEntries() bool {
|
|
||||||
return len(d.Entries) > 0
|
|
||||||
}
|
|
||||||
|
|
||||||
func (d DynamicSamplingContext) IsFrozen() bool {
|
|
||||||
return d.Frozen
|
|
||||||
}
|
|
||||||
|
|
||||||
func (d DynamicSamplingContext) String() string {
|
|
||||||
members := []baggage.Member{}
|
|
||||||
for k, entry := range d.Entries {
|
|
||||||
member, err := baggage.NewMember(sentryPrefix+k, entry)
|
|
||||||
if err != nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
members = append(members, member)
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(members) == 0 {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
baggage, err := baggage.New(members...)
|
|
||||||
if err != nil {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
return baggage.String()
|
|
||||||
}
|
|
||||||
|
|
||||||
// Constructs a new DynamicSamplingContext using a scope and client. Accessing
|
|
||||||
// fields on the scope are not thread safe, and this function should only be
|
|
||||||
// called within scope methods.
|
|
||||||
func DynamicSamplingContextFromScope(scope *Scope, client *Client) DynamicSamplingContext {
|
|
||||||
entries := map[string]string{}
|
|
||||||
|
|
||||||
if client == nil || scope == nil {
|
|
||||||
return DynamicSamplingContext{
|
|
||||||
Entries: entries,
|
|
||||||
Frozen: false,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
propagationContext := scope.propagationContext
|
|
||||||
|
|
||||||
if traceID := propagationContext.TraceID.String(); traceID != "" {
|
|
||||||
entries["trace_id"] = traceID
|
|
||||||
}
|
|
||||||
if sampleRate := client.options.TracesSampleRate; sampleRate != 0 {
|
|
||||||
entries["sample_rate"] = strconv.FormatFloat(sampleRate, 'f', -1, 64)
|
|
||||||
}
|
|
||||||
|
|
||||||
if dsn := client.dsn; dsn != nil {
|
|
||||||
if publicKey := dsn.publicKey; publicKey != "" {
|
|
||||||
entries["public_key"] = publicKey
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if release := client.options.Release; release != "" {
|
|
||||||
entries["release"] = release
|
|
||||||
}
|
|
||||||
if environment := client.options.Environment; environment != "" {
|
|
||||||
entries["environment"] = environment
|
|
||||||
}
|
|
||||||
|
|
||||||
return DynamicSamplingContext{
|
|
||||||
Entries: entries,
|
|
||||||
Frozen: true,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-21
@@ -1,21 +0,0 @@
|
|||||||
MIT License
|
|
||||||
|
|
||||||
Copyright (c) 2019 Functional Software, Inc. dba Sentry
|
|
||||||
|
|
||||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
||||||
of this software and associated documentation files (the "Software"), to deal
|
|
||||||
in the Software without restriction, including without limitation the rights
|
|
||||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
||||||
copies of the Software, and to permit persons to whom the Software is
|
|
||||||
furnished to do so, subject to the following conditions:
|
|
||||||
|
|
||||||
The above copyright notice and this permission notice shall be included in all
|
|
||||||
copies or substantial portions of the Software.
|
|
||||||
|
|
||||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
||||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
||||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
||||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
||||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
||||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
||||||
SOFTWARE.
|
|
||||||
-135
@@ -1,135 +0,0 @@
|
|||||||
<p align="center">
|
|
||||||
<a href="https://sentry.io" target="_blank" align="center">
|
|
||||||
<img src="https://sentry-brand.storage.googleapis.com/sentry-logo-black.png" width="280">
|
|
||||||
</a>
|
|
||||||
<br />
|
|
||||||
</p>
|
|
||||||
|
|
||||||
# Official Sentry Echo Handler for Sentry-go SDK
|
|
||||||
|
|
||||||
**go.dev:** https://pkg.go.dev/github.com/getsentry/sentry-go/echo
|
|
||||||
|
|
||||||
**Example:** https://github.com/getsentry/sentry-go/tree/master/_examples/echo
|
|
||||||
|
|
||||||
## Installation
|
|
||||||
|
|
||||||
```sh
|
|
||||||
go get github.com/getsentry/sentry-go/echo
|
|
||||||
```
|
|
||||||
|
|
||||||
```go
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"net/http"
|
|
||||||
|
|
||||||
"github.com/getsentry/sentry-go"
|
|
||||||
sentryecho "github.com/getsentry/sentry-go/echo"
|
|
||||||
"github.com/labstack/echo/v4"
|
|
||||||
"github.com/labstack/echo/v4/middleware"
|
|
||||||
)
|
|
||||||
|
|
||||||
// To initialize Sentry's handler, you need to initialize Sentry itself beforehand
|
|
||||||
if err := sentry.Init(sentry.ClientOptions{
|
|
||||||
Dsn: "your-public-dsn",
|
|
||||||
}); err != nil {
|
|
||||||
fmt.Printf("Sentry initialization failed: %v\n", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Then create your app
|
|
||||||
app := echo.New()
|
|
||||||
|
|
||||||
app.Use(middleware.Logger())
|
|
||||||
app.Use(middleware.Recover())
|
|
||||||
|
|
||||||
// Once it's done, you can attach the handler as one of your middleware
|
|
||||||
app.Use(sentryecho.New(sentryecho.Options{}))
|
|
||||||
|
|
||||||
// Set up routes
|
|
||||||
app.GET("/", func(ctx echo.Context) error {
|
|
||||||
return ctx.String(http.StatusOK, "Hello, World!")
|
|
||||||
})
|
|
||||||
|
|
||||||
// And run it
|
|
||||||
app.Logger.Fatal(app.Start(":3000"))
|
|
||||||
```
|
|
||||||
|
|
||||||
## Configuration
|
|
||||||
|
|
||||||
`sentryecho` accepts a struct of `Options` that allows you to configure how the handler will behave.
|
|
||||||
|
|
||||||
Currently it respects 3 options:
|
|
||||||
|
|
||||||
```go
|
|
||||||
// Repanic configures whether Sentry should repanic after recovery, in most cases it should be set to true,
|
|
||||||
// as echo includes its own Recover middleware that handles http responses.
|
|
||||||
Repanic bool
|
|
||||||
// WaitForDelivery configures whether you want to block the request before moving forward with the response.
|
|
||||||
// Because Echo's `Recover` handler doesn't restart the application,
|
|
||||||
// it's safe to either skip this option or set it to `false`.
|
|
||||||
WaitForDelivery bool
|
|
||||||
// Timeout for the event delivery requests.
|
|
||||||
Timeout time.Duration
|
|
||||||
```
|
|
||||||
|
|
||||||
## Usage
|
|
||||||
|
|
||||||
`sentryecho` attaches an instance of `*sentry.Hub` (https://pkg.go.dev/github.com/getsentry/sentry-go#Hub) to the `echo.Context`, which makes it available throughout the rest of the request's lifetime.
|
|
||||||
You can access it by using the `sentryecho.GetHubFromContext()` method on the context itself in any of your proceeding middleware and routes.
|
|
||||||
And it should be used instead of the global `sentry.CaptureMessage`, `sentry.CaptureException`, or any other calls, as it keeps the separation of data between the requests.
|
|
||||||
|
|
||||||
**Keep in mind that `*sentry.Hub` won't be available in middleware attached before to `sentryecho`!**
|
|
||||||
|
|
||||||
```go
|
|
||||||
app := echo.New()
|
|
||||||
|
|
||||||
app.Use(middleware.Logger())
|
|
||||||
app.Use(middleware.Recover())
|
|
||||||
|
|
||||||
app.Use(sentryecho.New(sentryecho.Options{
|
|
||||||
Repanic: true,
|
|
||||||
}))
|
|
||||||
|
|
||||||
app.Use(func(next echo.HandlerFunc) echo.HandlerFunc {
|
|
||||||
return func(ctx echo.Context) error {
|
|
||||||
if hub := sentryecho.GetHubFromContext(ctx); hub != nil {
|
|
||||||
hub.Scope().SetTag("someRandomTag", "maybeYouNeedIt")
|
|
||||||
}
|
|
||||||
return next(ctx)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
app.GET("/", func(ctx echo.Context) error {
|
|
||||||
if hub := sentryecho.GetHubFromContext(ctx); hub != nil {
|
|
||||||
hub.WithScope(func(scope *sentry.Scope) {
|
|
||||||
scope.SetExtra("unwantedQuery", "someQueryDataMaybe")
|
|
||||||
hub.CaptureMessage("User provided unwanted query string, but we recovered just fine")
|
|
||||||
})
|
|
||||||
}
|
|
||||||
return ctx.String(http.StatusOK, "Hello, World!")
|
|
||||||
})
|
|
||||||
|
|
||||||
app.GET("/foo", func(ctx echo.Context) error {
|
|
||||||
// sentryecho handler will catch it just fine. Also, because we attached "someRandomTag"
|
|
||||||
// in the middleware before, it will be sent through as well
|
|
||||||
panic("y tho")
|
|
||||||
})
|
|
||||||
|
|
||||||
app.Logger.Fatal(app.Start(":3000"))
|
|
||||||
```
|
|
||||||
|
|
||||||
### Accessing Request in `BeforeSend` callback
|
|
||||||
|
|
||||||
```go
|
|
||||||
sentry.Init(sentry.ClientOptions{
|
|
||||||
Dsn: "your-public-dsn",
|
|
||||||
BeforeSend: func(event *sentry.Event, hint *sentry.EventHint) *sentry.Event {
|
|
||||||
if hint.Context != nil {
|
|
||||||
if req, ok := hint.Context.Value(sentry.RequestContextKey).(*http.Request); ok {
|
|
||||||
// You have access to the original Request here
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return event
|
|
||||||
},
|
|
||||||
})
|
|
||||||
```
|
|
||||||
-158
@@ -1,158 +0,0 @@
|
|||||||
package sentryecho
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"fmt"
|
|
||||||
"net/http"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/getsentry/sentry-go"
|
|
||||||
"github.com/labstack/echo/v4"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
// sdkIdentifier is the identifier of the Echo SDK.
|
|
||||||
sdkIdentifier = "sentry.go.echo"
|
|
||||||
|
|
||||||
// valuesKey is used as a key to store the Sentry Hub instance on the echo.Context.
|
|
||||||
valuesKey = "sentry"
|
|
||||||
|
|
||||||
// transactionKey is used as a key to store the Sentry transaction on the echo.Context.
|
|
||||||
transactionKey = "sentry_transaction"
|
|
||||||
|
|
||||||
// errorKey is used as a key to store the error on the echo.Context.
|
|
||||||
errorKey = "error"
|
|
||||||
)
|
|
||||||
|
|
||||||
type handler struct {
|
|
||||||
repanic bool
|
|
||||||
waitForDelivery bool
|
|
||||||
timeout time.Duration
|
|
||||||
}
|
|
||||||
|
|
||||||
type Options struct {
|
|
||||||
// Repanic configures whether Sentry should repanic after recovery, in most cases it should be set to true,
|
|
||||||
// as Echo includes its own Recover middleware that handles HTTP responses.
|
|
||||||
Repanic bool
|
|
||||||
// WaitForDelivery configures whether you want to block the request before moving forward with the response.
|
|
||||||
// Because Echo's Recover handler doesn't restart the application,
|
|
||||||
// it's safe to either skip this option or set it to false.
|
|
||||||
WaitForDelivery bool
|
|
||||||
// Timeout for the event delivery requests.
|
|
||||||
Timeout time.Duration
|
|
||||||
}
|
|
||||||
|
|
||||||
// New returns a function that satisfies echo.HandlerFunc interface
|
|
||||||
// It can be used with Use() methods.
|
|
||||||
func New(options Options) echo.MiddlewareFunc {
|
|
||||||
if options.Timeout == 0 {
|
|
||||||
options.Timeout = 2 * time.Second
|
|
||||||
}
|
|
||||||
|
|
||||||
return (&handler{
|
|
||||||
repanic: options.Repanic,
|
|
||||||
timeout: options.Timeout,
|
|
||||||
waitForDelivery: options.WaitForDelivery,
|
|
||||||
}).handle
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *handler) handle(next echo.HandlerFunc) echo.HandlerFunc {
|
|
||||||
return func(ctx echo.Context) error {
|
|
||||||
hub := GetHubFromContext(ctx)
|
|
||||||
if hub == nil {
|
|
||||||
hub = sentry.CurrentHub().Clone()
|
|
||||||
}
|
|
||||||
|
|
||||||
if client := hub.Client(); client != nil {
|
|
||||||
client.SetSDKIdentifier(sdkIdentifier)
|
|
||||||
}
|
|
||||||
|
|
||||||
r := ctx.Request()
|
|
||||||
|
|
||||||
transactionName := r.URL.Path
|
|
||||||
transactionSource := sentry.SourceURL
|
|
||||||
|
|
||||||
if path := ctx.Path(); path != "" {
|
|
||||||
transactionName = path
|
|
||||||
transactionSource = sentry.SourceRoute
|
|
||||||
}
|
|
||||||
|
|
||||||
options := []sentry.SpanOption{
|
|
||||||
sentry.ContinueTrace(hub, r.Header.Get(sentry.SentryTraceHeader), r.Header.Get(sentry.SentryBaggageHeader)),
|
|
||||||
sentry.WithOpName("http.server"),
|
|
||||||
sentry.WithTransactionSource(transactionSource),
|
|
||||||
sentry.WithSpanOrigin(sentry.SpanOriginEcho),
|
|
||||||
}
|
|
||||||
|
|
||||||
transaction := sentry.StartTransaction(
|
|
||||||
sentry.SetHubOnContext(r.Context(), hub),
|
|
||||||
fmt.Sprintf("%s %s", r.Method, transactionName),
|
|
||||||
options...,
|
|
||||||
)
|
|
||||||
|
|
||||||
transaction.SetData("http.request.method", r.Method)
|
|
||||||
|
|
||||||
defer func() {
|
|
||||||
status := ctx.Response().Status
|
|
||||||
if err := ctx.Get(errorKey); err != nil {
|
|
||||||
if httpError, ok := err.(*echo.HTTPError); ok {
|
|
||||||
status = httpError.Code
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
transaction.Status = sentry.HTTPtoSpanStatus(status)
|
|
||||||
transaction.SetData("http.response.status_code", status)
|
|
||||||
transaction.Finish()
|
|
||||||
}()
|
|
||||||
|
|
||||||
hub.Scope().SetRequest(r)
|
|
||||||
ctx.Set(valuesKey, hub)
|
|
||||||
ctx.Set(transactionKey, transaction)
|
|
||||||
defer h.recoverWithSentry(hub, r)
|
|
||||||
|
|
||||||
err := next(ctx)
|
|
||||||
if err != nil {
|
|
||||||
// Store the error so it can be used in the deferred function
|
|
||||||
ctx.Set(errorKey, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *handler) recoverWithSentry(hub *sentry.Hub, r *http.Request) {
|
|
||||||
if err := recover(); err != nil {
|
|
||||||
eventID := hub.RecoverWithContext(
|
|
||||||
context.WithValue(r.Context(), sentry.RequestContextKey, r),
|
|
||||||
err,
|
|
||||||
)
|
|
||||||
if eventID != nil && h.waitForDelivery {
|
|
||||||
hub.Flush(h.timeout)
|
|
||||||
}
|
|
||||||
if h.repanic {
|
|
||||||
panic(err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetHubFromContext retrieves attached *sentry.Hub instance from echo.Context.
|
|
||||||
func GetHubFromContext(ctx echo.Context) *sentry.Hub {
|
|
||||||
if hub, ok := ctx.Get(valuesKey).(*sentry.Hub); ok {
|
|
||||||
return hub
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetHubOnContext attaches *sentry.Hub instance to echo.Context.
|
|
||||||
func SetHubOnContext(ctx echo.Context, hub *sentry.Hub) {
|
|
||||||
ctx.Set(valuesKey, hub)
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetSpanFromContext retrieves attached *sentry.Span instance from echo.Context.
|
|
||||||
// If there is no transaction on echo.Context, it will return nil.
|
|
||||||
func GetSpanFromContext(ctx echo.Context) *sentry.Span {
|
|
||||||
if span, ok := ctx.Get(transactionKey).(*sentry.Span); ok {
|
|
||||||
return span
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
-423
@@ -1,423 +0,0 @@
|
|||||||
package sentry
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"fmt"
|
|
||||||
"sync"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
type contextKey int
|
|
||||||
|
|
||||||
// Keys used to store values in a Context. Use with Context.Value to access
|
|
||||||
// values stored by the SDK.
|
|
||||||
const (
|
|
||||||
// HubContextKey is the key used to store the current Hub.
|
|
||||||
HubContextKey = contextKey(1)
|
|
||||||
// RequestContextKey is the key used to store the current http.Request.
|
|
||||||
RequestContextKey = contextKey(2)
|
|
||||||
)
|
|
||||||
|
|
||||||
// defaultMaxBreadcrumbs is the default maximum number of breadcrumbs added to
|
|
||||||
// an event. Can be overwritten with the maxBreadcrumbs option.
|
|
||||||
const defaultMaxBreadcrumbs = 30
|
|
||||||
|
|
||||||
// maxBreadcrumbs is the absolute maximum number of breadcrumbs added to an
|
|
||||||
// event. The maxBreadcrumbs option cannot be set higher than this value.
|
|
||||||
const maxBreadcrumbs = 100
|
|
||||||
|
|
||||||
// currentHub is the initial Hub with no Client bound and an empty Scope.
|
|
||||||
var currentHub = NewHub(nil, NewScope())
|
|
||||||
|
|
||||||
// Hub is the central object that manages scopes and clients.
|
|
||||||
//
|
|
||||||
// This can be used to capture events and manage the scope.
|
|
||||||
// The default hub that is available automatically.
|
|
||||||
//
|
|
||||||
// In most situations developers do not need to interface the hub. Instead
|
|
||||||
// toplevel convenience functions are exposed that will automatically dispatch
|
|
||||||
// to global (CurrentHub) hub. In some situations this might not be
|
|
||||||
// possible in which case it might become necessary to manually work with the
|
|
||||||
// hub. This is for instance the case when working with async code.
|
|
||||||
type Hub struct {
|
|
||||||
mu sync.RWMutex
|
|
||||||
stack *stack
|
|
||||||
lastEventID EventID
|
|
||||||
}
|
|
||||||
|
|
||||||
type layer struct {
|
|
||||||
// mu protects concurrent reads and writes to client.
|
|
||||||
mu sync.RWMutex
|
|
||||||
client *Client
|
|
||||||
// scope is read-only, not protected by mu.
|
|
||||||
scope *Scope
|
|
||||||
}
|
|
||||||
|
|
||||||
// Client returns the layer's client. Safe for concurrent use.
|
|
||||||
func (l *layer) Client() *Client {
|
|
||||||
l.mu.RLock()
|
|
||||||
defer l.mu.RUnlock()
|
|
||||||
return l.client
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetClient sets the layer's client. Safe for concurrent use.
|
|
||||||
func (l *layer) SetClient(c *Client) {
|
|
||||||
l.mu.Lock()
|
|
||||||
defer l.mu.Unlock()
|
|
||||||
l.client = c
|
|
||||||
}
|
|
||||||
|
|
||||||
type stack []*layer
|
|
||||||
|
|
||||||
// NewHub returns an instance of a Hub with provided Client and Scope bound.
|
|
||||||
func NewHub(client *Client, scope *Scope) *Hub {
|
|
||||||
hub := Hub{
|
|
||||||
stack: &stack{{
|
|
||||||
client: client,
|
|
||||||
scope: scope,
|
|
||||||
}},
|
|
||||||
}
|
|
||||||
return &hub
|
|
||||||
}
|
|
||||||
|
|
||||||
// CurrentHub returns an instance of previously initialized Hub stored in the global namespace.
|
|
||||||
func CurrentHub() *Hub {
|
|
||||||
return currentHub
|
|
||||||
}
|
|
||||||
|
|
||||||
// LastEventID returns the ID of the last event (error or message) captured
|
|
||||||
// through the hub and sent to the underlying transport.
|
|
||||||
//
|
|
||||||
// Transactions and events dropped by sampling or event processors do not change
|
|
||||||
// the last event ID.
|
|
||||||
//
|
|
||||||
// LastEventID is a convenience method to cover use cases in which errors are
|
|
||||||
// captured indirectly and the ID is needed. For example, it can be used as part
|
|
||||||
// of an HTTP middleware to log the ID of the last error, if any.
|
|
||||||
//
|
|
||||||
// For more flexibility, consider instead using the ClientOptions.BeforeSend
|
|
||||||
// function or event processors.
|
|
||||||
func (hub *Hub) LastEventID() EventID {
|
|
||||||
hub.mu.RLock()
|
|
||||||
defer hub.mu.RUnlock()
|
|
||||||
|
|
||||||
return hub.lastEventID
|
|
||||||
}
|
|
||||||
|
|
||||||
// stackTop returns the top layer of the hub stack. Valid hubs always have at
|
|
||||||
// least one layer, therefore stackTop always return a non-nil pointer.
|
|
||||||
func (hub *Hub) stackTop() *layer {
|
|
||||||
hub.mu.RLock()
|
|
||||||
defer hub.mu.RUnlock()
|
|
||||||
|
|
||||||
stack := hub.stack
|
|
||||||
stackLen := len(*stack)
|
|
||||||
top := (*stack)[stackLen-1]
|
|
||||||
return top
|
|
||||||
}
|
|
||||||
|
|
||||||
// Clone returns a copy of the current Hub with top-most scope and client copied over.
|
|
||||||
func (hub *Hub) Clone() *Hub {
|
|
||||||
top := hub.stackTop()
|
|
||||||
scope := top.scope
|
|
||||||
if scope != nil {
|
|
||||||
scope = scope.Clone()
|
|
||||||
}
|
|
||||||
return NewHub(top.Client(), scope)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Scope returns top-level Scope of the current Hub or nil if no Scope is bound.
|
|
||||||
func (hub *Hub) Scope() *Scope {
|
|
||||||
top := hub.stackTop()
|
|
||||||
return top.scope
|
|
||||||
}
|
|
||||||
|
|
||||||
// Client returns top-level Client of the current Hub or nil if no Client is bound.
|
|
||||||
func (hub *Hub) Client() *Client {
|
|
||||||
top := hub.stackTop()
|
|
||||||
return top.Client()
|
|
||||||
}
|
|
||||||
|
|
||||||
// PushScope pushes a new scope for the current Hub and reuses previously bound Client.
|
|
||||||
func (hub *Hub) PushScope() *Scope {
|
|
||||||
top := hub.stackTop()
|
|
||||||
|
|
||||||
var scope *Scope
|
|
||||||
if top.scope != nil {
|
|
||||||
scope = top.scope.Clone()
|
|
||||||
} else {
|
|
||||||
scope = NewScope()
|
|
||||||
}
|
|
||||||
|
|
||||||
hub.mu.Lock()
|
|
||||||
defer hub.mu.Unlock()
|
|
||||||
|
|
||||||
*hub.stack = append(*hub.stack, &layer{
|
|
||||||
client: top.Client(),
|
|
||||||
scope: scope,
|
|
||||||
})
|
|
||||||
|
|
||||||
return scope
|
|
||||||
}
|
|
||||||
|
|
||||||
// PopScope drops the most recent scope.
|
|
||||||
//
|
|
||||||
// Calls to PopScope must be coordinated with PushScope. For most cases, using
|
|
||||||
// WithScope should be more convenient.
|
|
||||||
//
|
|
||||||
// Calls to PopScope that do not match previous calls to PushScope are silently
|
|
||||||
// ignored.
|
|
||||||
func (hub *Hub) PopScope() {
|
|
||||||
hub.mu.Lock()
|
|
||||||
defer hub.mu.Unlock()
|
|
||||||
|
|
||||||
stack := *hub.stack
|
|
||||||
stackLen := len(stack)
|
|
||||||
if stackLen > 1 {
|
|
||||||
// Never pop the last item off the stack, the stack should always have
|
|
||||||
// at least one item.
|
|
||||||
*hub.stack = stack[0 : stackLen-1]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// BindClient binds a new Client for the current Hub.
|
|
||||||
func (hub *Hub) BindClient(client *Client) {
|
|
||||||
top := hub.stackTop()
|
|
||||||
top.SetClient(client)
|
|
||||||
}
|
|
||||||
|
|
||||||
// WithScope runs f in an isolated temporary scope.
|
|
||||||
//
|
|
||||||
// It is useful when extra data should be sent with a single capture call, for
|
|
||||||
// instance a different level or tags.
|
|
||||||
//
|
|
||||||
// The scope passed to f starts as a clone of the current scope and can be
|
|
||||||
// freely modified without affecting the current scope.
|
|
||||||
//
|
|
||||||
// It is a shorthand for PushScope followed by PopScope.
|
|
||||||
func (hub *Hub) WithScope(f func(scope *Scope)) {
|
|
||||||
scope := hub.PushScope()
|
|
||||||
defer hub.PopScope()
|
|
||||||
f(scope)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ConfigureScope runs f in the current scope.
|
|
||||||
//
|
|
||||||
// It is useful to set data that applies to all events that share the current
|
|
||||||
// scope.
|
|
||||||
//
|
|
||||||
// Modifying the scope affects all references to the current scope.
|
|
||||||
//
|
|
||||||
// See also WithScope for making isolated temporary changes.
|
|
||||||
func (hub *Hub) ConfigureScope(f func(scope *Scope)) {
|
|
||||||
scope := hub.Scope()
|
|
||||||
f(scope)
|
|
||||||
}
|
|
||||||
|
|
||||||
// CaptureEvent calls the method of a same name on currently bound Client instance
|
|
||||||
// passing it a top-level Scope.
|
|
||||||
// Returns EventID if successfully, or nil if there's no Scope or Client available.
|
|
||||||
func (hub *Hub) CaptureEvent(event *Event) *EventID {
|
|
||||||
client, scope := hub.Client(), hub.Scope()
|
|
||||||
if client == nil || scope == nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
eventID := client.CaptureEvent(event, nil, scope)
|
|
||||||
|
|
||||||
if event.Type != transactionType && eventID != nil {
|
|
||||||
hub.mu.Lock()
|
|
||||||
hub.lastEventID = *eventID
|
|
||||||
hub.mu.Unlock()
|
|
||||||
}
|
|
||||||
return eventID
|
|
||||||
}
|
|
||||||
|
|
||||||
// CaptureMessage calls the method of a same name on currently bound Client instance
|
|
||||||
// passing it a top-level Scope.
|
|
||||||
// Returns EventID if successfully, or nil if there's no Scope or Client available.
|
|
||||||
func (hub *Hub) CaptureMessage(message string) *EventID {
|
|
||||||
client, scope := hub.Client(), hub.Scope()
|
|
||||||
if client == nil || scope == nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
eventID := client.CaptureMessage(message, nil, scope)
|
|
||||||
|
|
||||||
if eventID != nil {
|
|
||||||
hub.mu.Lock()
|
|
||||||
hub.lastEventID = *eventID
|
|
||||||
hub.mu.Unlock()
|
|
||||||
}
|
|
||||||
return eventID
|
|
||||||
}
|
|
||||||
|
|
||||||
// CaptureException calls the method of a same name on currently bound Client instance
|
|
||||||
// passing it a top-level Scope.
|
|
||||||
// Returns EventID if successfully, or nil if there's no Scope or Client available.
|
|
||||||
func (hub *Hub) CaptureException(exception error) *EventID {
|
|
||||||
client, scope := hub.Client(), hub.Scope()
|
|
||||||
if client == nil || scope == nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
eventID := client.CaptureException(exception, &EventHint{OriginalException: exception}, scope)
|
|
||||||
|
|
||||||
if eventID != nil {
|
|
||||||
hub.mu.Lock()
|
|
||||||
hub.lastEventID = *eventID
|
|
||||||
hub.mu.Unlock()
|
|
||||||
}
|
|
||||||
return eventID
|
|
||||||
}
|
|
||||||
|
|
||||||
// CaptureCheckIn calls the method of the same name on currently bound Client instance
|
|
||||||
// passing it a top-level Scope.
|
|
||||||
// Returns CheckInID if the check-in was captured successfully, or nil otherwise.
|
|
||||||
func (hub *Hub) CaptureCheckIn(checkIn *CheckIn, monitorConfig *MonitorConfig) *EventID {
|
|
||||||
client, scope := hub.Client(), hub.Scope()
|
|
||||||
if client == nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
return client.CaptureCheckIn(checkIn, monitorConfig, scope)
|
|
||||||
}
|
|
||||||
|
|
||||||
// AddBreadcrumb records a new breadcrumb.
|
|
||||||
//
|
|
||||||
// The total number of breadcrumbs that can be recorded are limited by the
|
|
||||||
// configuration on the client.
|
|
||||||
func (hub *Hub) AddBreadcrumb(breadcrumb *Breadcrumb, hint *BreadcrumbHint) {
|
|
||||||
client := hub.Client()
|
|
||||||
|
|
||||||
// If there's no client, just store it on the scope straight away
|
|
||||||
if client == nil {
|
|
||||||
hub.Scope().AddBreadcrumb(breadcrumb, maxBreadcrumbs)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
max := client.options.MaxBreadcrumbs
|
|
||||||
switch {
|
|
||||||
case max < 0:
|
|
||||||
return
|
|
||||||
case max == 0:
|
|
||||||
max = defaultMaxBreadcrumbs
|
|
||||||
case max > maxBreadcrumbs:
|
|
||||||
max = maxBreadcrumbs
|
|
||||||
}
|
|
||||||
|
|
||||||
if client.options.BeforeBreadcrumb != nil {
|
|
||||||
if hint == nil {
|
|
||||||
hint = &BreadcrumbHint{}
|
|
||||||
}
|
|
||||||
if breadcrumb = client.options.BeforeBreadcrumb(breadcrumb, hint); breadcrumb == nil {
|
|
||||||
Logger.Println("breadcrumb dropped due to BeforeBreadcrumb callback.")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
hub.Scope().AddBreadcrumb(breadcrumb, max)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Recover calls the method of a same name on currently bound Client instance
|
|
||||||
// passing it a top-level Scope.
|
|
||||||
// Returns EventID if successfully, or nil if there's no Scope or Client available.
|
|
||||||
func (hub *Hub) Recover(err interface{}) *EventID {
|
|
||||||
if err == nil {
|
|
||||||
err = recover()
|
|
||||||
}
|
|
||||||
client, scope := hub.Client(), hub.Scope()
|
|
||||||
if client == nil || scope == nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return client.Recover(err, &EventHint{RecoveredException: err}, scope)
|
|
||||||
}
|
|
||||||
|
|
||||||
// RecoverWithContext calls the method of a same name on currently bound Client instance
|
|
||||||
// passing it a top-level Scope.
|
|
||||||
// Returns EventID if successfully, or nil if there's no Scope or Client available.
|
|
||||||
func (hub *Hub) RecoverWithContext(ctx context.Context, err interface{}) *EventID {
|
|
||||||
if err == nil {
|
|
||||||
err = recover()
|
|
||||||
}
|
|
||||||
client, scope := hub.Client(), hub.Scope()
|
|
||||||
if client == nil || scope == nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return client.RecoverWithContext(ctx, err, &EventHint{RecoveredException: err}, scope)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Flush waits until the underlying Transport sends any buffered events to the
|
|
||||||
// Sentry server, blocking for at most the given timeout. It returns false if
|
|
||||||
// the timeout was reached. In that case, some events may not have been sent.
|
|
||||||
//
|
|
||||||
// Flush should be called before terminating the program to avoid
|
|
||||||
// unintentionally dropping events.
|
|
||||||
//
|
|
||||||
// Do not call Flush indiscriminately after every call to CaptureEvent,
|
|
||||||
// CaptureException or CaptureMessage. Instead, to have the SDK send events over
|
|
||||||
// the network synchronously, configure it to use the HTTPSyncTransport in the
|
|
||||||
// call to Init.
|
|
||||||
func (hub *Hub) Flush(timeout time.Duration) bool {
|
|
||||||
client := hub.Client()
|
|
||||||
|
|
||||||
if client == nil {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
return client.Flush(timeout)
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetTraceparent returns the current Sentry traceparent string, to be used as a HTTP header value
|
|
||||||
// or HTML meta tag value.
|
|
||||||
// This function is context aware, as in it either returns the traceparent based
|
|
||||||
// on the current span, or the scope's propagation context.
|
|
||||||
func (hub *Hub) GetTraceparent() string {
|
|
||||||
scope := hub.Scope()
|
|
||||||
|
|
||||||
if scope.span != nil {
|
|
||||||
return scope.span.ToSentryTrace()
|
|
||||||
}
|
|
||||||
|
|
||||||
return fmt.Sprintf("%s-%s", scope.propagationContext.TraceID, scope.propagationContext.SpanID)
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetBaggage returns the current Sentry baggage string, to be used as a HTTP header value
|
|
||||||
// or HTML meta tag value.
|
|
||||||
// This function is context aware, as in it either returns the baggage based
|
|
||||||
// on the current span or the scope's propagation context.
|
|
||||||
func (hub *Hub) GetBaggage() string {
|
|
||||||
scope := hub.Scope()
|
|
||||||
|
|
||||||
if scope.span != nil {
|
|
||||||
return scope.span.ToBaggage()
|
|
||||||
}
|
|
||||||
|
|
||||||
return scope.propagationContext.DynamicSamplingContext.String()
|
|
||||||
}
|
|
||||||
|
|
||||||
// HasHubOnContext checks whether Hub instance is bound to a given Context struct.
|
|
||||||
func HasHubOnContext(ctx context.Context) bool {
|
|
||||||
_, ok := ctx.Value(HubContextKey).(*Hub)
|
|
||||||
return ok
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetHubFromContext tries to retrieve Hub instance from the given Context struct
|
|
||||||
// or return nil if one is not found.
|
|
||||||
func GetHubFromContext(ctx context.Context) *Hub {
|
|
||||||
if hub, ok := ctx.Value(HubContextKey).(*Hub); ok {
|
|
||||||
return hub
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// hubFromContext returns either a hub stored in the context or the current hub.
|
|
||||||
// The return value is guaranteed to be non-nil, unlike GetHubFromContext.
|
|
||||||
func hubFromContext(ctx context.Context) *Hub {
|
|
||||||
if hub, ok := ctx.Value(HubContextKey).(*Hub); ok {
|
|
||||||
return hub
|
|
||||||
}
|
|
||||||
return currentHub
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetHubOnContext stores given Hub instance on the Context struct and returns a new Context.
|
|
||||||
func SetHubOnContext(ctx context.Context, hub *Hub) context.Context {
|
|
||||||
return context.WithValue(ctx, HubContextKey, hub)
|
|
||||||
}
|
|
||||||
-391
@@ -1,391 +0,0 @@
|
|||||||
package sentry
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"os"
|
|
||||||
"regexp"
|
|
||||||
"runtime"
|
|
||||||
"runtime/debug"
|
|
||||||
"strings"
|
|
||||||
"sync"
|
|
||||||
)
|
|
||||||
|
|
||||||
// ================================
|
|
||||||
// Modules Integration
|
|
||||||
// ================================
|
|
||||||
|
|
||||||
type modulesIntegration struct {
|
|
||||||
once sync.Once
|
|
||||||
modules map[string]string
|
|
||||||
}
|
|
||||||
|
|
||||||
func (mi *modulesIntegration) Name() string {
|
|
||||||
return "Modules"
|
|
||||||
}
|
|
||||||
|
|
||||||
func (mi *modulesIntegration) SetupOnce(client *Client) {
|
|
||||||
client.AddEventProcessor(mi.processor)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (mi *modulesIntegration) processor(event *Event, _ *EventHint) *Event {
|
|
||||||
if len(event.Modules) == 0 {
|
|
||||||
mi.once.Do(func() {
|
|
||||||
info, ok := debug.ReadBuildInfo()
|
|
||||||
if !ok {
|
|
||||||
Logger.Print("The Modules integration is not available in binaries built without module support.")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
mi.modules = extractModules(info)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
event.Modules = mi.modules
|
|
||||||
return event
|
|
||||||
}
|
|
||||||
|
|
||||||
func extractModules(info *debug.BuildInfo) map[string]string {
|
|
||||||
modules := map[string]string{
|
|
||||||
info.Main.Path: info.Main.Version,
|
|
||||||
}
|
|
||||||
for _, dep := range info.Deps {
|
|
||||||
ver := dep.Version
|
|
||||||
if dep.Replace != nil {
|
|
||||||
ver += fmt.Sprintf(" => %s %s", dep.Replace.Path, dep.Replace.Version)
|
|
||||||
}
|
|
||||||
modules[dep.Path] = strings.TrimSuffix(ver, " ")
|
|
||||||
}
|
|
||||||
return modules
|
|
||||||
}
|
|
||||||
|
|
||||||
// ================================
|
|
||||||
// Environment Integration
|
|
||||||
// ================================
|
|
||||||
|
|
||||||
type environmentIntegration struct{}
|
|
||||||
|
|
||||||
func (ei *environmentIntegration) Name() string {
|
|
||||||
return "Environment"
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ei *environmentIntegration) SetupOnce(client *Client) {
|
|
||||||
client.AddEventProcessor(ei.processor)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ei *environmentIntegration) processor(event *Event, _ *EventHint) *Event {
|
|
||||||
// Initialize maps as necessary.
|
|
||||||
contextNames := []string{"device", "os", "runtime"}
|
|
||||||
if event.Contexts == nil {
|
|
||||||
event.Contexts = make(map[string]Context, len(contextNames))
|
|
||||||
}
|
|
||||||
for _, name := range contextNames {
|
|
||||||
if event.Contexts[name] == nil {
|
|
||||||
event.Contexts[name] = make(Context)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Set contextual information preserving existing data. For each context, if
|
|
||||||
// the existing value is not of type map[string]interface{}, then no
|
|
||||||
// additional information is added.
|
|
||||||
if deviceContext, ok := event.Contexts["device"]; ok {
|
|
||||||
if _, ok := deviceContext["arch"]; !ok {
|
|
||||||
deviceContext["arch"] = runtime.GOARCH
|
|
||||||
}
|
|
||||||
if _, ok := deviceContext["num_cpu"]; !ok {
|
|
||||||
deviceContext["num_cpu"] = runtime.NumCPU()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if osContext, ok := event.Contexts["os"]; ok {
|
|
||||||
if _, ok := osContext["name"]; !ok {
|
|
||||||
osContext["name"] = runtime.GOOS
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if runtimeContext, ok := event.Contexts["runtime"]; ok {
|
|
||||||
if _, ok := runtimeContext["name"]; !ok {
|
|
||||||
runtimeContext["name"] = "go"
|
|
||||||
}
|
|
||||||
if _, ok := runtimeContext["version"]; !ok {
|
|
||||||
runtimeContext["version"] = runtime.Version()
|
|
||||||
}
|
|
||||||
if _, ok := runtimeContext["go_numroutines"]; !ok {
|
|
||||||
runtimeContext["go_numroutines"] = runtime.NumGoroutine()
|
|
||||||
}
|
|
||||||
if _, ok := runtimeContext["go_maxprocs"]; !ok {
|
|
||||||
runtimeContext["go_maxprocs"] = runtime.GOMAXPROCS(0)
|
|
||||||
}
|
|
||||||
if _, ok := runtimeContext["go_numcgocalls"]; !ok {
|
|
||||||
runtimeContext["go_numcgocalls"] = runtime.NumCgoCall()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return event
|
|
||||||
}
|
|
||||||
|
|
||||||
// ================================
|
|
||||||
// Ignore Errors Integration
|
|
||||||
// ================================
|
|
||||||
|
|
||||||
type ignoreErrorsIntegration struct {
|
|
||||||
ignoreErrors []*regexp.Regexp
|
|
||||||
}
|
|
||||||
|
|
||||||
func (iei *ignoreErrorsIntegration) Name() string {
|
|
||||||
return "IgnoreErrors"
|
|
||||||
}
|
|
||||||
|
|
||||||
func (iei *ignoreErrorsIntegration) SetupOnce(client *Client) {
|
|
||||||
iei.ignoreErrors = transformStringsIntoRegexps(client.options.IgnoreErrors)
|
|
||||||
client.AddEventProcessor(iei.processor)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (iei *ignoreErrorsIntegration) processor(event *Event, _ *EventHint) *Event {
|
|
||||||
suspects := getIgnoreErrorsSuspects(event)
|
|
||||||
|
|
||||||
for _, suspect := range suspects {
|
|
||||||
for _, pattern := range iei.ignoreErrors {
|
|
||||||
if pattern.Match([]byte(suspect)) || strings.Contains(suspect, pattern.String()) {
|
|
||||||
Logger.Printf("Event dropped due to being matched by `IgnoreErrors` option."+
|
|
||||||
"| Value matched: %s | Filter used: %s", suspect, pattern)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return event
|
|
||||||
}
|
|
||||||
|
|
||||||
func transformStringsIntoRegexps(strings []string) []*regexp.Regexp {
|
|
||||||
var exprs []*regexp.Regexp
|
|
||||||
|
|
||||||
for _, s := range strings {
|
|
||||||
r, err := regexp.Compile(s)
|
|
||||||
if err == nil {
|
|
||||||
exprs = append(exprs, r)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return exprs
|
|
||||||
}
|
|
||||||
|
|
||||||
func getIgnoreErrorsSuspects(event *Event) []string {
|
|
||||||
suspects := []string{}
|
|
||||||
|
|
||||||
if event.Message != "" {
|
|
||||||
suspects = append(suspects, event.Message)
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, ex := range event.Exception {
|
|
||||||
suspects = append(suspects, ex.Type, ex.Value)
|
|
||||||
}
|
|
||||||
|
|
||||||
return suspects
|
|
||||||
}
|
|
||||||
|
|
||||||
// ================================
|
|
||||||
// Ignore Transactions Integration
|
|
||||||
// ================================
|
|
||||||
|
|
||||||
type ignoreTransactionsIntegration struct {
|
|
||||||
ignoreTransactions []*regexp.Regexp
|
|
||||||
}
|
|
||||||
|
|
||||||
func (iei *ignoreTransactionsIntegration) Name() string {
|
|
||||||
return "IgnoreTransactions"
|
|
||||||
}
|
|
||||||
|
|
||||||
func (iei *ignoreTransactionsIntegration) SetupOnce(client *Client) {
|
|
||||||
iei.ignoreTransactions = transformStringsIntoRegexps(client.options.IgnoreTransactions)
|
|
||||||
client.AddEventProcessor(iei.processor)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (iei *ignoreTransactionsIntegration) processor(event *Event, _ *EventHint) *Event {
|
|
||||||
suspect := event.Transaction
|
|
||||||
if suspect == "" {
|
|
||||||
return event
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, pattern := range iei.ignoreTransactions {
|
|
||||||
if pattern.Match([]byte(suspect)) || strings.Contains(suspect, pattern.String()) {
|
|
||||||
Logger.Printf("Transaction dropped due to being matched by `IgnoreTransactions` option."+
|
|
||||||
"| Value matched: %s | Filter used: %s", suspect, pattern)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return event
|
|
||||||
}
|
|
||||||
|
|
||||||
// ================================
|
|
||||||
// Contextify Frames Integration
|
|
||||||
// ================================
|
|
||||||
|
|
||||||
type contextifyFramesIntegration struct {
|
|
||||||
sr sourceReader
|
|
||||||
contextLines int
|
|
||||||
cachedLocations sync.Map
|
|
||||||
}
|
|
||||||
|
|
||||||
func (cfi *contextifyFramesIntegration) Name() string {
|
|
||||||
return "ContextifyFrames"
|
|
||||||
}
|
|
||||||
|
|
||||||
func (cfi *contextifyFramesIntegration) SetupOnce(client *Client) {
|
|
||||||
cfi.sr = newSourceReader()
|
|
||||||
cfi.contextLines = 5
|
|
||||||
|
|
||||||
client.AddEventProcessor(cfi.processor)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (cfi *contextifyFramesIntegration) processor(event *Event, _ *EventHint) *Event {
|
|
||||||
// Range over all exceptions
|
|
||||||
for _, ex := range event.Exception {
|
|
||||||
// If it has no stacktrace, just bail out
|
|
||||||
if ex.Stacktrace == nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
// If it does, it should have frames, so try to contextify them
|
|
||||||
ex.Stacktrace.Frames = cfi.contextify(ex.Stacktrace.Frames)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Range over all threads
|
|
||||||
for _, th := range event.Threads {
|
|
||||||
// If it has no stacktrace, just bail out
|
|
||||||
if th.Stacktrace == nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
// If it does, it should have frames, so try to contextify them
|
|
||||||
th.Stacktrace.Frames = cfi.contextify(th.Stacktrace.Frames)
|
|
||||||
}
|
|
||||||
|
|
||||||
return event
|
|
||||||
}
|
|
||||||
|
|
||||||
func (cfi *contextifyFramesIntegration) contextify(frames []Frame) []Frame {
|
|
||||||
contextifiedFrames := make([]Frame, 0, len(frames))
|
|
||||||
|
|
||||||
for _, frame := range frames {
|
|
||||||
if !frame.InApp {
|
|
||||||
contextifiedFrames = append(contextifiedFrames, frame)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
var path string
|
|
||||||
|
|
||||||
if cachedPath, ok := cfi.cachedLocations.Load(frame.AbsPath); ok {
|
|
||||||
if p, ok := cachedPath.(string); ok {
|
|
||||||
path = p
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// Optimize for happy path here
|
|
||||||
if fileExists(frame.AbsPath) {
|
|
||||||
path = frame.AbsPath
|
|
||||||
} else {
|
|
||||||
path = cfi.findNearbySourceCodeLocation(frame.AbsPath)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if path == "" {
|
|
||||||
contextifiedFrames = append(contextifiedFrames, frame)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
lines, contextLine := cfi.sr.readContextLines(path, frame.Lineno, cfi.contextLines)
|
|
||||||
contextifiedFrames = append(contextifiedFrames, cfi.addContextLinesToFrame(frame, lines, contextLine))
|
|
||||||
}
|
|
||||||
|
|
||||||
return contextifiedFrames
|
|
||||||
}
|
|
||||||
|
|
||||||
func (cfi *contextifyFramesIntegration) findNearbySourceCodeLocation(originalPath string) string {
|
|
||||||
trimmedPath := strings.TrimPrefix(originalPath, "/")
|
|
||||||
components := strings.Split(trimmedPath, "/")
|
|
||||||
|
|
||||||
for len(components) > 0 {
|
|
||||||
components = components[1:]
|
|
||||||
possibleLocation := strings.Join(components, "/")
|
|
||||||
|
|
||||||
if fileExists(possibleLocation) {
|
|
||||||
cfi.cachedLocations.Store(originalPath, possibleLocation)
|
|
||||||
return possibleLocation
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
cfi.cachedLocations.Store(originalPath, "")
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
func (cfi *contextifyFramesIntegration) addContextLinesToFrame(frame Frame, lines [][]byte, contextLine int) Frame {
|
|
||||||
for i, line := range lines {
|
|
||||||
switch {
|
|
||||||
case i < contextLine:
|
|
||||||
frame.PreContext = append(frame.PreContext, string(line))
|
|
||||||
case i == contextLine:
|
|
||||||
frame.ContextLine = string(line)
|
|
||||||
default:
|
|
||||||
frame.PostContext = append(frame.PostContext, string(line))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return frame
|
|
||||||
}
|
|
||||||
|
|
||||||
// ================================
|
|
||||||
// Global Tags Integration
|
|
||||||
// ================================
|
|
||||||
|
|
||||||
const envTagsPrefix = "SENTRY_TAGS_"
|
|
||||||
|
|
||||||
type globalTagsIntegration struct {
|
|
||||||
tags map[string]string
|
|
||||||
envTags map[string]string
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ti *globalTagsIntegration) Name() string {
|
|
||||||
return "GlobalTags"
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ti *globalTagsIntegration) SetupOnce(client *Client) {
|
|
||||||
ti.tags = make(map[string]string, len(client.options.Tags))
|
|
||||||
for k, v := range client.options.Tags {
|
|
||||||
ti.tags[k] = v
|
|
||||||
}
|
|
||||||
|
|
||||||
ti.envTags = loadEnvTags()
|
|
||||||
|
|
||||||
client.AddEventProcessor(ti.processor)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ti *globalTagsIntegration) processor(event *Event, _ *EventHint) *Event {
|
|
||||||
if len(ti.tags) == 0 && len(ti.envTags) == 0 {
|
|
||||||
return event
|
|
||||||
}
|
|
||||||
|
|
||||||
if event.Tags == nil {
|
|
||||||
event.Tags = make(map[string]string, len(ti.tags)+len(ti.envTags))
|
|
||||||
}
|
|
||||||
|
|
||||||
for k, v := range ti.tags {
|
|
||||||
if _, ok := event.Tags[k]; !ok {
|
|
||||||
event.Tags[k] = v
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for k, v := range ti.envTags {
|
|
||||||
if _, ok := event.Tags[k]; !ok {
|
|
||||||
event.Tags[k] = v
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return event
|
|
||||||
}
|
|
||||||
|
|
||||||
func loadEnvTags() map[string]string {
|
|
||||||
tags := map[string]string{}
|
|
||||||
for _, pair := range os.Environ() {
|
|
||||||
parts := strings.Split(pair, "=")
|
|
||||||
if !strings.HasPrefix(parts[0], envTagsPrefix) {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
tag := strings.TrimPrefix(parts[0], envTagsPrefix)
|
|
||||||
tags[tag] = parts[1]
|
|
||||||
}
|
|
||||||
return tags
|
|
||||||
}
|
|
||||||
-549
@@ -1,549 +0,0 @@
|
|||||||
package sentry
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"encoding/json"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"net"
|
|
||||||
"net/http"
|
|
||||||
"reflect"
|
|
||||||
"slices"
|
|
||||||
"strings"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
// eventType is the type of an error event.
|
|
||||||
const eventType = "event"
|
|
||||||
|
|
||||||
// transactionType is the type of a transaction event.
|
|
||||||
const transactionType = "transaction"
|
|
||||||
|
|
||||||
// checkInType is the type of a check in event.
|
|
||||||
const checkInType = "check_in"
|
|
||||||
|
|
||||||
// Level marks the severity of the event.
|
|
||||||
type Level string
|
|
||||||
|
|
||||||
// Describes the severity of the event.
|
|
||||||
const (
|
|
||||||
LevelDebug Level = "debug"
|
|
||||||
LevelInfo Level = "info"
|
|
||||||
LevelWarning Level = "warning"
|
|
||||||
LevelError Level = "error"
|
|
||||||
LevelFatal Level = "fatal"
|
|
||||||
)
|
|
||||||
|
|
||||||
// SdkInfo contains all metadata about about the SDK being used.
|
|
||||||
type SdkInfo struct {
|
|
||||||
Name string `json:"name,omitempty"`
|
|
||||||
Version string `json:"version,omitempty"`
|
|
||||||
Integrations []string `json:"integrations,omitempty"`
|
|
||||||
Packages []SdkPackage `json:"packages,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// SdkPackage describes a package that was installed.
|
|
||||||
type SdkPackage struct {
|
|
||||||
Name string `json:"name,omitempty"`
|
|
||||||
Version string `json:"version,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// TODO: This type could be more useful, as map of interface{} is too generic
|
|
||||||
// and requires a lot of type assertions in beforeBreadcrumb calls
|
|
||||||
// plus it could just be map[string]interface{} then.
|
|
||||||
|
|
||||||
// BreadcrumbHint contains information that can be associated with a Breadcrumb.
|
|
||||||
type BreadcrumbHint map[string]interface{}
|
|
||||||
|
|
||||||
// Breadcrumb specifies an application event that occurred before a Sentry event.
|
|
||||||
// An event may contain one or more breadcrumbs.
|
|
||||||
type Breadcrumb struct {
|
|
||||||
Type string `json:"type,omitempty"`
|
|
||||||
Category string `json:"category,omitempty"`
|
|
||||||
Message string `json:"message,omitempty"`
|
|
||||||
Data map[string]interface{} `json:"data,omitempty"`
|
|
||||||
Level Level `json:"level,omitempty"`
|
|
||||||
Timestamp time.Time `json:"timestamp"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// TODO: provide constants for known breadcrumb types.
|
|
||||||
// See https://develop.sentry.dev/sdk/event-payloads/breadcrumbs/#breadcrumb-types.
|
|
||||||
|
|
||||||
// MarshalJSON converts the Breadcrumb struct to JSON.
|
|
||||||
func (b *Breadcrumb) MarshalJSON() ([]byte, error) {
|
|
||||||
// We want to omit time.Time zero values, otherwise the server will try to
|
|
||||||
// interpret dates too far in the past. However, encoding/json doesn't
|
|
||||||
// support the "omitempty" option for struct types. See
|
|
||||||
// https://golang.org/issues/11939.
|
|
||||||
//
|
|
||||||
// We overcome the limitation and achieve what we want by shadowing fields
|
|
||||||
// and a few type tricks.
|
|
||||||
|
|
||||||
// breadcrumb aliases Breadcrumb to allow calling json.Marshal without an
|
|
||||||
// infinite loop. It preserves all fields while none of the attached
|
|
||||||
// methods.
|
|
||||||
type breadcrumb Breadcrumb
|
|
||||||
|
|
||||||
if b.Timestamp.IsZero() {
|
|
||||||
return json.Marshal(struct {
|
|
||||||
// Embed all of the fields of Breadcrumb.
|
|
||||||
*breadcrumb
|
|
||||||
// Timestamp shadows the original Timestamp field and is meant to
|
|
||||||
// remain nil, triggering the omitempty behavior.
|
|
||||||
Timestamp json.RawMessage `json:"timestamp,omitempty"`
|
|
||||||
}{breadcrumb: (*breadcrumb)(b)})
|
|
||||||
}
|
|
||||||
return json.Marshal((*breadcrumb)(b))
|
|
||||||
}
|
|
||||||
|
|
||||||
// Attachment allows associating files with your events to aid in investigation.
|
|
||||||
// An event may contain one or more attachments.
|
|
||||||
type Attachment struct {
|
|
||||||
Filename string
|
|
||||||
ContentType string
|
|
||||||
Payload []byte
|
|
||||||
}
|
|
||||||
|
|
||||||
// User describes the user associated with an Event. If this is used, at least
|
|
||||||
// an ID or an IP address should be provided.
|
|
||||||
type User struct {
|
|
||||||
ID string `json:"id,omitempty"`
|
|
||||||
Email string `json:"email,omitempty"`
|
|
||||||
IPAddress string `json:"ip_address,omitempty"`
|
|
||||||
Username string `json:"username,omitempty"`
|
|
||||||
Name string `json:"name,omitempty"`
|
|
||||||
Data map[string]string `json:"data,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (u User) IsEmpty() bool {
|
|
||||||
if u.ID != "" {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
if u.Email != "" {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
if u.IPAddress != "" {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
if u.Username != "" {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
if u.Name != "" {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(u.Data) > 0 {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
// Request contains information on a HTTP request related to the event.
|
|
||||||
type Request struct {
|
|
||||||
URL string `json:"url,omitempty"`
|
|
||||||
Method string `json:"method,omitempty"`
|
|
||||||
Data string `json:"data,omitempty"`
|
|
||||||
QueryString string `json:"query_string,omitempty"`
|
|
||||||
Cookies string `json:"cookies,omitempty"`
|
|
||||||
Headers map[string]string `json:"headers,omitempty"`
|
|
||||||
Env map[string]string `json:"env,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
var sensitiveHeaders = map[string]struct{}{
|
|
||||||
"Authorization": {},
|
|
||||||
"Proxy-Authorization": {},
|
|
||||||
"Cookie": {},
|
|
||||||
"X-Forwarded-For": {},
|
|
||||||
"X-Real-Ip": {},
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewRequest returns a new Sentry Request from the given http.Request.
|
|
||||||
//
|
|
||||||
// NewRequest avoids operations that depend on network access. In particular, it
|
|
||||||
// does not read r.Body.
|
|
||||||
func NewRequest(r *http.Request) *Request {
|
|
||||||
protocol := schemeHTTP
|
|
||||||
if r.TLS != nil || r.Header.Get("X-Forwarded-Proto") == "https" {
|
|
||||||
protocol = schemeHTTPS
|
|
||||||
}
|
|
||||||
url := fmt.Sprintf("%s://%s%s", protocol, r.Host, r.URL.Path)
|
|
||||||
|
|
||||||
var cookies string
|
|
||||||
var env map[string]string
|
|
||||||
headers := map[string]string{}
|
|
||||||
|
|
||||||
if client := CurrentHub().Client(); client != nil && client.options.SendDefaultPII {
|
|
||||||
// We read only the first Cookie header because of the specification:
|
|
||||||
// https://tools.ietf.org/html/rfc6265#section-5.4
|
|
||||||
// When the user agent generates an HTTP request, the user agent MUST NOT
|
|
||||||
// attach more than one Cookie header field.
|
|
||||||
cookies = r.Header.Get("Cookie")
|
|
||||||
|
|
||||||
headers = make(map[string]string, len(r.Header))
|
|
||||||
for k, v := range r.Header {
|
|
||||||
headers[k] = strings.Join(v, ",")
|
|
||||||
}
|
|
||||||
|
|
||||||
if addr, port, err := net.SplitHostPort(r.RemoteAddr); err == nil {
|
|
||||||
env = map[string]string{"REMOTE_ADDR": addr, "REMOTE_PORT": port}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
for k, v := range r.Header {
|
|
||||||
if _, ok := sensitiveHeaders[k]; !ok {
|
|
||||||
headers[k] = strings.Join(v, ",")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
headers["Host"] = r.Host
|
|
||||||
|
|
||||||
return &Request{
|
|
||||||
URL: url,
|
|
||||||
Method: r.Method,
|
|
||||||
QueryString: r.URL.RawQuery,
|
|
||||||
Cookies: cookies,
|
|
||||||
Headers: headers,
|
|
||||||
Env: env,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Mechanism is the mechanism by which an exception was generated and handled.
|
|
||||||
type Mechanism struct {
|
|
||||||
Type string `json:"type,omitempty"`
|
|
||||||
Description string `json:"description,omitempty"`
|
|
||||||
HelpLink string `json:"help_link,omitempty"`
|
|
||||||
Source string `json:"source,omitempty"`
|
|
||||||
Handled *bool `json:"handled,omitempty"`
|
|
||||||
ParentID *int `json:"parent_id,omitempty"`
|
|
||||||
ExceptionID int `json:"exception_id"`
|
|
||||||
IsExceptionGroup bool `json:"is_exception_group,omitempty"`
|
|
||||||
Data map[string]any `json:"data,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetUnhandled indicates that the exception is an unhandled exception, i.e.
|
|
||||||
// from a panic.
|
|
||||||
func (m *Mechanism) SetUnhandled() {
|
|
||||||
m.Handled = Pointer(false)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Exception specifies an error that occurred.
|
|
||||||
type Exception struct {
|
|
||||||
Type string `json:"type,omitempty"` // used as the main issue title
|
|
||||||
Value string `json:"value,omitempty"` // used as the main issue subtitle
|
|
||||||
Module string `json:"module,omitempty"`
|
|
||||||
ThreadID uint64 `json:"thread_id,omitempty"`
|
|
||||||
Stacktrace *Stacktrace `json:"stacktrace,omitempty"`
|
|
||||||
Mechanism *Mechanism `json:"mechanism,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// SDKMetaData is a struct to stash data which is needed at some point in the SDK's event processing pipeline
|
|
||||||
// but which shouldn't get send to Sentry.
|
|
||||||
type SDKMetaData struct {
|
|
||||||
dsc DynamicSamplingContext
|
|
||||||
}
|
|
||||||
|
|
||||||
// Contains information about how the name of the transaction was determined.
|
|
||||||
type TransactionInfo struct {
|
|
||||||
Source TransactionSource `json:"source,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// The DebugMeta interface is not used in Golang apps, but may be populated
|
|
||||||
// when proxying Events from other platforms, like iOS, Android, and the
|
|
||||||
// Web. (See: https://develop.sentry.dev/sdk/event-payloads/debugmeta/ ).
|
|
||||||
type DebugMeta struct {
|
|
||||||
SdkInfo *DebugMetaSdkInfo `json:"sdk_info,omitempty"`
|
|
||||||
Images []DebugMetaImage `json:"images,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type DebugMetaSdkInfo struct {
|
|
||||||
SdkName string `json:"sdk_name,omitempty"`
|
|
||||||
VersionMajor int `json:"version_major,omitempty"`
|
|
||||||
VersionMinor int `json:"version_minor,omitempty"`
|
|
||||||
VersionPatchlevel int `json:"version_patchlevel,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type DebugMetaImage struct {
|
|
||||||
Type string `json:"type,omitempty"` // all
|
|
||||||
ImageAddr string `json:"image_addr,omitempty"` // macho,elf,pe
|
|
||||||
ImageSize int `json:"image_size,omitempty"` // macho,elf,pe
|
|
||||||
DebugID string `json:"debug_id,omitempty"` // macho,elf,pe,wasm,sourcemap
|
|
||||||
DebugFile string `json:"debug_file,omitempty"` // macho,elf,pe,wasm
|
|
||||||
CodeID string `json:"code_id,omitempty"` // macho,elf,pe,wasm
|
|
||||||
CodeFile string `json:"code_file,omitempty"` // macho,elf,pe,wasm,sourcemap
|
|
||||||
ImageVmaddr string `json:"image_vmaddr,omitempty"` // macho,elf,pe
|
|
||||||
Arch string `json:"arch,omitempty"` // macho,elf,pe
|
|
||||||
UUID string `json:"uuid,omitempty"` // proguard
|
|
||||||
}
|
|
||||||
|
|
||||||
// EventID is a hexadecimal string representing a unique uuid4 for an Event.
|
|
||||||
// An EventID must be 32 characters long, lowercase and not have any dashes.
|
|
||||||
type EventID string
|
|
||||||
|
|
||||||
type Context = map[string]interface{}
|
|
||||||
|
|
||||||
// Event is the fundamental data structure that is sent to Sentry.
|
|
||||||
type Event struct {
|
|
||||||
Breadcrumbs []*Breadcrumb `json:"breadcrumbs,omitempty"`
|
|
||||||
Contexts map[string]Context `json:"contexts,omitempty"`
|
|
||||||
Dist string `json:"dist,omitempty"`
|
|
||||||
Environment string `json:"environment,omitempty"`
|
|
||||||
EventID EventID `json:"event_id,omitempty"`
|
|
||||||
Extra map[string]interface{} `json:"extra,omitempty"`
|
|
||||||
Fingerprint []string `json:"fingerprint,omitempty"`
|
|
||||||
Level Level `json:"level,omitempty"`
|
|
||||||
Message string `json:"message,omitempty"`
|
|
||||||
Platform string `json:"platform,omitempty"`
|
|
||||||
Release string `json:"release,omitempty"`
|
|
||||||
Sdk SdkInfo `json:"sdk,omitempty"`
|
|
||||||
ServerName string `json:"server_name,omitempty"`
|
|
||||||
Threads []Thread `json:"threads,omitempty"`
|
|
||||||
Tags map[string]string `json:"tags,omitempty"`
|
|
||||||
Timestamp time.Time `json:"timestamp"`
|
|
||||||
Transaction string `json:"transaction,omitempty"`
|
|
||||||
User User `json:"user,omitempty"`
|
|
||||||
Logger string `json:"logger,omitempty"`
|
|
||||||
Modules map[string]string `json:"modules,omitempty"`
|
|
||||||
Request *Request `json:"request,omitempty"`
|
|
||||||
Exception []Exception `json:"exception,omitempty"`
|
|
||||||
DebugMeta *DebugMeta `json:"debug_meta,omitempty"`
|
|
||||||
Attachments []*Attachment `json:"-"`
|
|
||||||
|
|
||||||
// The fields below are only relevant for transactions.
|
|
||||||
|
|
||||||
Type string `json:"type,omitempty"`
|
|
||||||
StartTime time.Time `json:"start_timestamp"`
|
|
||||||
Spans []*Span `json:"spans,omitempty"`
|
|
||||||
TransactionInfo *TransactionInfo `json:"transaction_info,omitempty"`
|
|
||||||
|
|
||||||
// The fields below are only relevant for crons/check ins
|
|
||||||
|
|
||||||
CheckIn *CheckIn `json:"check_in,omitempty"`
|
|
||||||
MonitorConfig *MonitorConfig `json:"monitor_config,omitempty"`
|
|
||||||
|
|
||||||
// The fields below are not part of the final JSON payload.
|
|
||||||
|
|
||||||
sdkMetaData SDKMetaData
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetException appends the unwrapped errors to the event's exception list.
|
|
||||||
//
|
|
||||||
// maxErrorDepth is the maximum depth of the error chain we will look
|
|
||||||
// into while unwrapping the errors. If maxErrorDepth is -1, we will
|
|
||||||
// unwrap all errors in the chain.
|
|
||||||
func (e *Event) SetException(exception error, maxErrorDepth int) {
|
|
||||||
if exception == nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
err := exception
|
|
||||||
|
|
||||||
for i := 0; err != nil && (i < maxErrorDepth || maxErrorDepth == -1); i++ {
|
|
||||||
// Add the current error to the exception slice with its details
|
|
||||||
e.Exception = append(e.Exception, Exception{
|
|
||||||
Value: err.Error(),
|
|
||||||
Type: reflect.TypeOf(err).String(),
|
|
||||||
Stacktrace: ExtractStacktrace(err),
|
|
||||||
})
|
|
||||||
|
|
||||||
// Attempt to unwrap the error using the standard library's Unwrap method.
|
|
||||||
// If errors.Unwrap returns nil, it means either there is no error to unwrap,
|
|
||||||
// or the error does not implement the Unwrap method.
|
|
||||||
unwrappedErr := errors.Unwrap(err)
|
|
||||||
|
|
||||||
if unwrappedErr != nil {
|
|
||||||
// The error was successfully unwrapped using the standard library's Unwrap method.
|
|
||||||
err = unwrappedErr
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
cause, ok := err.(interface{ Cause() error })
|
|
||||||
if !ok {
|
|
||||||
// We cannot unwrap the error further.
|
|
||||||
break
|
|
||||||
}
|
|
||||||
|
|
||||||
// The error implements the Cause method, indicating it may have been wrapped
|
|
||||||
// using the github.com/pkg/errors package.
|
|
||||||
err = cause.Cause()
|
|
||||||
}
|
|
||||||
|
|
||||||
// Add a trace of the current stack to the most recent error in a chain if
|
|
||||||
// it doesn't have a stack trace yet.
|
|
||||||
// We only add to the most recent error to avoid duplication and because the
|
|
||||||
// current stack is most likely unrelated to errors deeper in the chain.
|
|
||||||
if e.Exception[0].Stacktrace == nil {
|
|
||||||
e.Exception[0].Stacktrace = NewStacktrace()
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(e.Exception) <= 1 {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// event.Exception should be sorted such that the most recent error is last.
|
|
||||||
slices.Reverse(e.Exception)
|
|
||||||
|
|
||||||
for i := range e.Exception {
|
|
||||||
e.Exception[i].Mechanism = &Mechanism{
|
|
||||||
IsExceptionGroup: true,
|
|
||||||
ExceptionID: i,
|
|
||||||
Type: "generic",
|
|
||||||
}
|
|
||||||
if i == 0 {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
e.Exception[i].Mechanism.ParentID = Pointer(i - 1)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TODO: Event.Contexts map[string]interface{} => map[string]EventContext,
|
|
||||||
// to prevent accidentally storing T when we mean *T.
|
|
||||||
// For example, the TraceContext must be stored as *TraceContext to pick up the
|
|
||||||
// MarshalJSON method (and avoid copying).
|
|
||||||
// type EventContext interface{ EventContext() }
|
|
||||||
|
|
||||||
// MarshalJSON converts the Event struct to JSON.
|
|
||||||
func (e *Event) MarshalJSON() ([]byte, error) {
|
|
||||||
// We want to omit time.Time zero values, otherwise the server will try to
|
|
||||||
// interpret dates too far in the past. However, encoding/json doesn't
|
|
||||||
// support the "omitempty" option for struct types. See
|
|
||||||
// https://golang.org/issues/11939.
|
|
||||||
//
|
|
||||||
// We overcome the limitation and achieve what we want by shadowing fields
|
|
||||||
// and a few type tricks.
|
|
||||||
if e.Type == transactionType {
|
|
||||||
return e.transactionMarshalJSON()
|
|
||||||
}
|
|
||||||
|
|
||||||
if e.Type == checkInType {
|
|
||||||
return e.checkInMarshalJSON()
|
|
||||||
}
|
|
||||||
return e.defaultMarshalJSON()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e *Event) defaultMarshalJSON() ([]byte, error) {
|
|
||||||
// event aliases Event to allow calling json.Marshal without an infinite
|
|
||||||
// loop. It preserves all fields while none of the attached methods.
|
|
||||||
type event Event
|
|
||||||
|
|
||||||
// errorEvent is like Event with shadowed fields for customizing JSON
|
|
||||||
// marshaling.
|
|
||||||
type errorEvent struct {
|
|
||||||
*event
|
|
||||||
|
|
||||||
// Timestamp shadows the original Timestamp field. It allows us to
|
|
||||||
// include the timestamp when non-zero and omit it otherwise.
|
|
||||||
Timestamp json.RawMessage `json:"timestamp,omitempty"`
|
|
||||||
|
|
||||||
// The fields below are not part of error events and only make sense to
|
|
||||||
// be sent for transactions. They shadow the respective fields in Event
|
|
||||||
// and are meant to remain nil, triggering the omitempty behavior.
|
|
||||||
|
|
||||||
Type json.RawMessage `json:"type,omitempty"`
|
|
||||||
StartTime json.RawMessage `json:"start_timestamp,omitempty"`
|
|
||||||
Spans json.RawMessage `json:"spans,omitempty"`
|
|
||||||
TransactionInfo json.RawMessage `json:"transaction_info,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
x := errorEvent{event: (*event)(e)}
|
|
||||||
if !e.Timestamp.IsZero() {
|
|
||||||
b, err := e.Timestamp.MarshalJSON()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
x.Timestamp = b
|
|
||||||
}
|
|
||||||
return json.Marshal(x)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e *Event) transactionMarshalJSON() ([]byte, error) {
|
|
||||||
// event aliases Event to allow calling json.Marshal without an infinite
|
|
||||||
// loop. It preserves all fields while none of the attached methods.
|
|
||||||
type event Event
|
|
||||||
|
|
||||||
// transactionEvent is like Event with shadowed fields for customizing JSON
|
|
||||||
// marshaling.
|
|
||||||
type transactionEvent struct {
|
|
||||||
*event
|
|
||||||
|
|
||||||
// The fields below shadow the respective fields in Event. They allow us
|
|
||||||
// to include timestamps when non-zero and omit them otherwise.
|
|
||||||
|
|
||||||
StartTime json.RawMessage `json:"start_timestamp,omitempty"`
|
|
||||||
Timestamp json.RawMessage `json:"timestamp,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
x := transactionEvent{event: (*event)(e)}
|
|
||||||
if !e.Timestamp.IsZero() {
|
|
||||||
b, err := e.Timestamp.MarshalJSON()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
x.Timestamp = b
|
|
||||||
}
|
|
||||||
if !e.StartTime.IsZero() {
|
|
||||||
b, err := e.StartTime.MarshalJSON()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
x.StartTime = b
|
|
||||||
}
|
|
||||||
return json.Marshal(x)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e *Event) checkInMarshalJSON() ([]byte, error) {
|
|
||||||
checkIn := serializedCheckIn{
|
|
||||||
CheckInID: string(e.CheckIn.ID),
|
|
||||||
MonitorSlug: e.CheckIn.MonitorSlug,
|
|
||||||
Status: e.CheckIn.Status,
|
|
||||||
Duration: e.CheckIn.Duration.Seconds(),
|
|
||||||
Release: e.Release,
|
|
||||||
Environment: e.Environment,
|
|
||||||
MonitorConfig: nil,
|
|
||||||
}
|
|
||||||
|
|
||||||
if e.MonitorConfig != nil {
|
|
||||||
checkIn.MonitorConfig = &MonitorConfig{
|
|
||||||
Schedule: e.MonitorConfig.Schedule,
|
|
||||||
CheckInMargin: e.MonitorConfig.CheckInMargin,
|
|
||||||
MaxRuntime: e.MonitorConfig.MaxRuntime,
|
|
||||||
Timezone: e.MonitorConfig.Timezone,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return json.Marshal(checkIn)
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewEvent creates a new Event.
|
|
||||||
func NewEvent() *Event {
|
|
||||||
return &Event{
|
|
||||||
Contexts: make(map[string]Context),
|
|
||||||
Extra: make(map[string]interface{}),
|
|
||||||
Tags: make(map[string]string),
|
|
||||||
Modules: make(map[string]string),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Thread specifies threads that were running at the time of an event.
|
|
||||||
type Thread struct {
|
|
||||||
ID string `json:"id,omitempty"`
|
|
||||||
Name string `json:"name,omitempty"`
|
|
||||||
Stacktrace *Stacktrace `json:"stacktrace,omitempty"`
|
|
||||||
Crashed bool `json:"crashed,omitempty"`
|
|
||||||
Current bool `json:"current,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// EventHint contains information that can be associated with an Event.
|
|
||||||
type EventHint struct {
|
|
||||||
Data interface{}
|
|
||||||
EventID string
|
|
||||||
OriginalException error
|
|
||||||
RecoveredException interface{}
|
|
||||||
Context context.Context
|
|
||||||
Request *http.Request
|
|
||||||
Response *http.Response
|
|
||||||
}
|
|
||||||
-79
@@ -1,79 +0,0 @@
|
|||||||
package debug
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
"net/http"
|
|
||||||
"net/http/httptrace"
|
|
||||||
"net/http/httputil"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Transport implements http.RoundTripper and can be used to wrap other HTTP
|
|
||||||
// transports for debugging, normally http.DefaultTransport.
|
|
||||||
type Transport struct {
|
|
||||||
http.RoundTripper
|
|
||||||
Output io.Writer
|
|
||||||
// Dump controls whether to dump HTTP request and responses.
|
|
||||||
Dump bool
|
|
||||||
// Trace enables usage of net/http/httptrace.
|
|
||||||
Trace bool
|
|
||||||
}
|
|
||||||
|
|
||||||
func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) {
|
|
||||||
var buf bytes.Buffer
|
|
||||||
if t.Dump {
|
|
||||||
b, err := httputil.DumpRequestOut(req, true)
|
|
||||||
if err != nil {
|
|
||||||
panic(err)
|
|
||||||
}
|
|
||||||
_, err = buf.Write(ensureTrailingNewline(b))
|
|
||||||
if err != nil {
|
|
||||||
panic(err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if t.Trace {
|
|
||||||
trace := &httptrace.ClientTrace{
|
|
||||||
DNSDone: func(di httptrace.DNSDoneInfo) {
|
|
||||||
fmt.Fprintf(&buf, "* DNS %v → %v\n", req.Host, di.Addrs)
|
|
||||||
},
|
|
||||||
GotConn: func(ci httptrace.GotConnInfo) {
|
|
||||||
fmt.Fprintf(&buf, "* Connection local=%v remote=%v", ci.Conn.LocalAddr(), ci.Conn.RemoteAddr())
|
|
||||||
if ci.Reused {
|
|
||||||
fmt.Fprint(&buf, " (reused)")
|
|
||||||
}
|
|
||||||
if ci.WasIdle {
|
|
||||||
fmt.Fprintf(&buf, " (idle %v)", ci.IdleTime)
|
|
||||||
}
|
|
||||||
fmt.Fprintln(&buf)
|
|
||||||
},
|
|
||||||
}
|
|
||||||
req = req.WithContext(httptrace.WithClientTrace(req.Context(), trace))
|
|
||||||
}
|
|
||||||
resp, err := t.RoundTripper.RoundTrip(req)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if t.Dump {
|
|
||||||
b, err := httputil.DumpResponse(resp, true)
|
|
||||||
if err != nil {
|
|
||||||
panic(err)
|
|
||||||
}
|
|
||||||
_, err = buf.Write(ensureTrailingNewline(b))
|
|
||||||
if err != nil {
|
|
||||||
panic(err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
_, err = io.Copy(t.Output, &buf)
|
|
||||||
if err != nil {
|
|
||||||
panic(err)
|
|
||||||
}
|
|
||||||
return resp, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func ensureTrailingNewline(b []byte) []byte {
|
|
||||||
if len(b) > 0 && b[len(b)-1] != '\n' {
|
|
||||||
b = append(b, '\n')
|
|
||||||
}
|
|
||||||
return b
|
|
||||||
}
|
|
||||||
-12
@@ -1,12 +0,0 @@
|
|||||||
## Why do we have this "otel/baggage" folder?
|
|
||||||
|
|
||||||
The root sentry-go SDK (namely, the Dynamic Sampling functionality) needs an implementation of the [baggage spec](https://www.w3.org/TR/baggage/).
|
|
||||||
For that reason, we've taken the existing baggage implementation from the [opentelemetry-go](https://github.com/open-telemetry/opentelemetry-go/) repository, and fixed a few things that in our opinion were violating the specification.
|
|
||||||
|
|
||||||
These issues are:
|
|
||||||
1. Baggage string value `one%20two` should be properly parsed as "one two"
|
|
||||||
1. Baggage string value `one+two` should be parsed as "one+two"
|
|
||||||
1. Go string value "one two" should be encoded as `one%20two` (percent encoding), and NOT as `one+two` (URL query encoding).
|
|
||||||
1. Go string value "1=1" might be encoded as `1=1`, because the spec says: "Note, value MAY contain any number of the equal sign (=) characters. Parsers MUST NOT assume that the equal sign is only used to separate key and value.". `1%3D1` is also valid, but to simplify the implementation we're not doing it.
|
|
||||||
|
|
||||||
Changes were made in this PR: https://github.com/getsentry/sentry-go/pull/568
|
|
||||||
-604
@@ -1,604 +0,0 @@
|
|||||||
// Adapted from https://github.com/open-telemetry/opentelemetry-go/blob/c21b6b6bb31a2f74edd06e262f1690f3f6ea3d5c/baggage/baggage.go
|
|
||||||
//
|
|
||||||
// Copyright The OpenTelemetry Authors
|
|
||||||
//
|
|
||||||
// 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.
|
|
||||||
|
|
||||||
package baggage
|
|
||||||
|
|
||||||
import (
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"net/url"
|
|
||||||
"regexp"
|
|
||||||
"strings"
|
|
||||||
"unicode/utf8"
|
|
||||||
|
|
||||||
"github.com/getsentry/sentry-go/internal/otel/baggage/internal/baggage"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
maxMembers = 180
|
|
||||||
maxBytesPerMembers = 4096
|
|
||||||
maxBytesPerBaggageString = 8192
|
|
||||||
|
|
||||||
listDelimiter = ","
|
|
||||||
keyValueDelimiter = "="
|
|
||||||
propertyDelimiter = ";"
|
|
||||||
|
|
||||||
keyDef = `([\x21\x23-\x27\x2A\x2B\x2D\x2E\x30-\x39\x41-\x5a\x5e-\x7a\x7c\x7e]+)`
|
|
||||||
valueDef = `([\x21\x23-\x2b\x2d-\x3a\x3c-\x5B\x5D-\x7e]*)`
|
|
||||||
keyValueDef = `\s*` + keyDef + `\s*` + keyValueDelimiter + `\s*` + valueDef + `\s*`
|
|
||||||
)
|
|
||||||
|
|
||||||
var (
|
|
||||||
keyRe = regexp.MustCompile(`^` + keyDef + `$`)
|
|
||||||
valueRe = regexp.MustCompile(`^` + valueDef + `$`)
|
|
||||||
propertyRe = regexp.MustCompile(`^(?:\s*` + keyDef + `\s*|` + keyValueDef + `)$`)
|
|
||||||
)
|
|
||||||
|
|
||||||
var (
|
|
||||||
errInvalidKey = errors.New("invalid key")
|
|
||||||
errInvalidValue = errors.New("invalid value")
|
|
||||||
errInvalidProperty = errors.New("invalid baggage list-member property")
|
|
||||||
errInvalidMember = errors.New("invalid baggage list-member")
|
|
||||||
errMemberNumber = errors.New("too many list-members in baggage-string")
|
|
||||||
errMemberBytes = errors.New("list-member too large")
|
|
||||||
errBaggageBytes = errors.New("baggage-string too large")
|
|
||||||
)
|
|
||||||
|
|
||||||
// Property is an additional metadata entry for a baggage list-member.
|
|
||||||
type Property struct {
|
|
||||||
key, value string
|
|
||||||
|
|
||||||
// hasValue indicates if a zero-value value means the property does not
|
|
||||||
// have a value or if it was the zero-value.
|
|
||||||
hasValue bool
|
|
||||||
|
|
||||||
// hasData indicates whether the created property contains data or not.
|
|
||||||
// Properties that do not contain data are invalid with no other check
|
|
||||||
// required.
|
|
||||||
hasData bool
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewKeyProperty returns a new Property for key.
|
|
||||||
//
|
|
||||||
// If key is invalid, an error will be returned.
|
|
||||||
func NewKeyProperty(key string) (Property, error) {
|
|
||||||
if !keyRe.MatchString(key) {
|
|
||||||
return newInvalidProperty(), fmt.Errorf("%w: %q", errInvalidKey, key)
|
|
||||||
}
|
|
||||||
|
|
||||||
p := Property{key: key, hasData: true}
|
|
||||||
return p, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewKeyValueProperty returns a new Property for key with value.
|
|
||||||
//
|
|
||||||
// If key or value are invalid, an error will be returned.
|
|
||||||
func NewKeyValueProperty(key, value string) (Property, error) {
|
|
||||||
if !keyRe.MatchString(key) {
|
|
||||||
return newInvalidProperty(), fmt.Errorf("%w: %q", errInvalidKey, key)
|
|
||||||
}
|
|
||||||
if !valueRe.MatchString(value) {
|
|
||||||
return newInvalidProperty(), fmt.Errorf("%w: %q", errInvalidValue, value)
|
|
||||||
}
|
|
||||||
|
|
||||||
p := Property{
|
|
||||||
key: key,
|
|
||||||
value: value,
|
|
||||||
hasValue: true,
|
|
||||||
hasData: true,
|
|
||||||
}
|
|
||||||
return p, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func newInvalidProperty() Property {
|
|
||||||
return Property{}
|
|
||||||
}
|
|
||||||
|
|
||||||
// parseProperty attempts to decode a Property from the passed string. It
|
|
||||||
// returns an error if the input is invalid according to the W3C Baggage
|
|
||||||
// specification.
|
|
||||||
func parseProperty(property string) (Property, error) {
|
|
||||||
if property == "" {
|
|
||||||
return newInvalidProperty(), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
match := propertyRe.FindStringSubmatch(property)
|
|
||||||
if len(match) != 4 {
|
|
||||||
return newInvalidProperty(), fmt.Errorf("%w: %q", errInvalidProperty, property)
|
|
||||||
}
|
|
||||||
|
|
||||||
p := Property{hasData: true}
|
|
||||||
if match[1] != "" {
|
|
||||||
p.key = match[1]
|
|
||||||
} else {
|
|
||||||
p.key = match[2]
|
|
||||||
p.value = match[3]
|
|
||||||
p.hasValue = true
|
|
||||||
}
|
|
||||||
|
|
||||||
return p, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// validate ensures p conforms to the W3C Baggage specification, returning an
|
|
||||||
// error otherwise.
|
|
||||||
func (p Property) validate() error {
|
|
||||||
errFunc := func(err error) error {
|
|
||||||
return fmt.Errorf("invalid property: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if !p.hasData {
|
|
||||||
return errFunc(fmt.Errorf("%w: %q", errInvalidProperty, p))
|
|
||||||
}
|
|
||||||
|
|
||||||
if !keyRe.MatchString(p.key) {
|
|
||||||
return errFunc(fmt.Errorf("%w: %q", errInvalidKey, p.key))
|
|
||||||
}
|
|
||||||
if p.hasValue && !valueRe.MatchString(p.value) {
|
|
||||||
return errFunc(fmt.Errorf("%w: %q", errInvalidValue, p.value))
|
|
||||||
}
|
|
||||||
if !p.hasValue && p.value != "" {
|
|
||||||
return errFunc(errors.New("inconsistent value"))
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Key returns the Property key.
|
|
||||||
func (p Property) Key() string {
|
|
||||||
return p.key
|
|
||||||
}
|
|
||||||
|
|
||||||
// Value returns the Property value. Additionally, a boolean value is returned
|
|
||||||
// indicating if the returned value is the empty if the Property has a value
|
|
||||||
// that is empty or if the value is not set.
|
|
||||||
func (p Property) Value() (string, bool) {
|
|
||||||
return p.value, p.hasValue
|
|
||||||
}
|
|
||||||
|
|
||||||
// String encodes Property into a string compliant with the W3C Baggage
|
|
||||||
// specification.
|
|
||||||
func (p Property) String() string {
|
|
||||||
if p.hasValue {
|
|
||||||
return fmt.Sprintf("%s%s%v", p.key, keyValueDelimiter, p.value)
|
|
||||||
}
|
|
||||||
return p.key
|
|
||||||
}
|
|
||||||
|
|
||||||
type properties []Property
|
|
||||||
|
|
||||||
func fromInternalProperties(iProps []baggage.Property) properties {
|
|
||||||
if len(iProps) == 0 {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
props := make(properties, len(iProps))
|
|
||||||
for i, p := range iProps {
|
|
||||||
props[i] = Property{
|
|
||||||
key: p.Key,
|
|
||||||
value: p.Value,
|
|
||||||
hasValue: p.HasValue,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return props
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p properties) asInternal() []baggage.Property {
|
|
||||||
if len(p) == 0 {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
iProps := make([]baggage.Property, len(p))
|
|
||||||
for i, prop := range p {
|
|
||||||
iProps[i] = baggage.Property{
|
|
||||||
Key: prop.key,
|
|
||||||
Value: prop.value,
|
|
||||||
HasValue: prop.hasValue,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return iProps
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p properties) Copy() properties {
|
|
||||||
if len(p) == 0 {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
props := make(properties, len(p))
|
|
||||||
copy(props, p)
|
|
||||||
return props
|
|
||||||
}
|
|
||||||
|
|
||||||
// validate ensures each Property in p conforms to the W3C Baggage
|
|
||||||
// specification, returning an error otherwise.
|
|
||||||
func (p properties) validate() error {
|
|
||||||
for _, prop := range p {
|
|
||||||
if err := prop.validate(); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// String encodes properties into a string compliant with the W3C Baggage
|
|
||||||
// specification.
|
|
||||||
func (p properties) String() string {
|
|
||||||
props := make([]string, len(p))
|
|
||||||
for i, prop := range p {
|
|
||||||
props[i] = prop.String()
|
|
||||||
}
|
|
||||||
return strings.Join(props, propertyDelimiter)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Member is a list-member of a baggage-string as defined by the W3C Baggage
|
|
||||||
// specification.
|
|
||||||
type Member struct {
|
|
||||||
key, value string
|
|
||||||
properties properties
|
|
||||||
|
|
||||||
// hasData indicates whether the created property contains data or not.
|
|
||||||
// Properties that do not contain data are invalid with no other check
|
|
||||||
// required.
|
|
||||||
hasData bool
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewMember returns a new Member from the passed arguments. The key will be
|
|
||||||
// used directly while the value will be url decoded after validation. An error
|
|
||||||
// is returned if the created Member would be invalid according to the W3C
|
|
||||||
// Baggage specification.
|
|
||||||
func NewMember(key, value string, props ...Property) (Member, error) {
|
|
||||||
m := Member{
|
|
||||||
key: key,
|
|
||||||
value: value,
|
|
||||||
properties: properties(props).Copy(),
|
|
||||||
hasData: true,
|
|
||||||
}
|
|
||||||
if err := m.validate(); err != nil {
|
|
||||||
return newInvalidMember(), err
|
|
||||||
}
|
|
||||||
//// NOTE(anton): I don't think we need to unescape here
|
|
||||||
// decodedValue, err := url.PathUnescape(value)
|
|
||||||
// if err != nil {
|
|
||||||
// return newInvalidMember(), fmt.Errorf("%w: %q", errInvalidValue, value)
|
|
||||||
// }
|
|
||||||
// m.value = decodedValue
|
|
||||||
return m, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func newInvalidMember() Member {
|
|
||||||
return Member{}
|
|
||||||
}
|
|
||||||
|
|
||||||
// parseMember attempts to decode a Member from the passed string. It returns
|
|
||||||
// an error if the input is invalid according to the W3C Baggage
|
|
||||||
// specification.
|
|
||||||
func parseMember(member string) (Member, error) {
|
|
||||||
if n := len(member); n > maxBytesPerMembers {
|
|
||||||
return newInvalidMember(), fmt.Errorf("%w: %d", errMemberBytes, n)
|
|
||||||
}
|
|
||||||
|
|
||||||
var (
|
|
||||||
key, value string
|
|
||||||
props properties
|
|
||||||
)
|
|
||||||
|
|
||||||
parts := strings.SplitN(member, propertyDelimiter, 2)
|
|
||||||
switch len(parts) {
|
|
||||||
case 2:
|
|
||||||
// Parse the member properties.
|
|
||||||
for _, pStr := range strings.Split(parts[1], propertyDelimiter) {
|
|
||||||
p, err := parseProperty(pStr)
|
|
||||||
if err != nil {
|
|
||||||
return newInvalidMember(), err
|
|
||||||
}
|
|
||||||
props = append(props, p)
|
|
||||||
}
|
|
||||||
fallthrough
|
|
||||||
case 1:
|
|
||||||
// Parse the member key/value pair.
|
|
||||||
|
|
||||||
// Take into account a value can contain equal signs (=).
|
|
||||||
kv := strings.SplitN(parts[0], keyValueDelimiter, 2)
|
|
||||||
if len(kv) != 2 {
|
|
||||||
return newInvalidMember(), fmt.Errorf("%w: %q", errInvalidMember, member)
|
|
||||||
}
|
|
||||||
// "Leading and trailing whitespaces are allowed but MUST be trimmed
|
|
||||||
// when converting the header into a data structure."
|
|
||||||
key = strings.TrimSpace(kv[0])
|
|
||||||
value = strings.TrimSpace(kv[1])
|
|
||||||
var err error
|
|
||||||
if !keyRe.MatchString(key) {
|
|
||||||
return newInvalidMember(), fmt.Errorf("%w: %q", errInvalidKey, key)
|
|
||||||
}
|
|
||||||
if !valueRe.MatchString(value) {
|
|
||||||
return newInvalidMember(), fmt.Errorf("%w: %q", errInvalidValue, value)
|
|
||||||
}
|
|
||||||
decodedValue, err := url.PathUnescape(value)
|
|
||||||
if err != nil {
|
|
||||||
return newInvalidMember(), fmt.Errorf("%w: %q", err, value)
|
|
||||||
}
|
|
||||||
value = decodedValue
|
|
||||||
default:
|
|
||||||
// This should never happen unless a developer has changed the string
|
|
||||||
// splitting somehow. Panic instead of failing silently and allowing
|
|
||||||
// the bug to slip past the CI checks.
|
|
||||||
panic("failed to parse baggage member")
|
|
||||||
}
|
|
||||||
|
|
||||||
return Member{key: key, value: value, properties: props, hasData: true}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// validate ensures m conforms to the W3C Baggage specification.
|
|
||||||
// A key is just an ASCII string, but a value must be URL encoded UTF-8,
|
|
||||||
// returning an error otherwise.
|
|
||||||
func (m Member) validate() error {
|
|
||||||
if !m.hasData {
|
|
||||||
return fmt.Errorf("%w: %q", errInvalidMember, m)
|
|
||||||
}
|
|
||||||
|
|
||||||
if !keyRe.MatchString(m.key) {
|
|
||||||
return fmt.Errorf("%w: %q", errInvalidKey, m.key)
|
|
||||||
}
|
|
||||||
//// NOTE(anton): IMO it's too early to validate the value here.
|
|
||||||
// if !valueRe.MatchString(m.value) {
|
|
||||||
// return fmt.Errorf("%w: %q", errInvalidValue, m.value)
|
|
||||||
// }
|
|
||||||
return m.properties.validate()
|
|
||||||
}
|
|
||||||
|
|
||||||
// Key returns the Member key.
|
|
||||||
func (m Member) Key() string { return m.key }
|
|
||||||
|
|
||||||
// Value returns the Member value.
|
|
||||||
func (m Member) Value() string { return m.value }
|
|
||||||
|
|
||||||
// Properties returns a copy of the Member properties.
|
|
||||||
func (m Member) Properties() []Property { return m.properties.Copy() }
|
|
||||||
|
|
||||||
// String encodes Member into a string compliant with the W3C Baggage
|
|
||||||
// specification.
|
|
||||||
func (m Member) String() string {
|
|
||||||
// A key is just an ASCII string, but a value is URL encoded UTF-8.
|
|
||||||
s := fmt.Sprintf("%s%s%s", m.key, keyValueDelimiter, percentEncodeValue(m.value))
|
|
||||||
if len(m.properties) > 0 {
|
|
||||||
s = fmt.Sprintf("%s%s%s", s, propertyDelimiter, m.properties.String())
|
|
||||||
}
|
|
||||||
return s
|
|
||||||
}
|
|
||||||
|
|
||||||
// percentEncodeValue encodes the baggage value, using percent-encoding for
|
|
||||||
// disallowed octets.
|
|
||||||
func percentEncodeValue(s string) string {
|
|
||||||
const upperhex = "0123456789ABCDEF"
|
|
||||||
var sb strings.Builder
|
|
||||||
|
|
||||||
for byteIndex, width := 0, 0; byteIndex < len(s); byteIndex += width {
|
|
||||||
runeValue, w := utf8.DecodeRuneInString(s[byteIndex:])
|
|
||||||
width = w
|
|
||||||
char := string(runeValue)
|
|
||||||
if valueRe.MatchString(char) && char != "%" {
|
|
||||||
// The character is returned as is, no need to percent-encode
|
|
||||||
sb.WriteString(char)
|
|
||||||
} else {
|
|
||||||
// We need to percent-encode each byte of the multi-octet character
|
|
||||||
for j := 0; j < width; j++ {
|
|
||||||
b := s[byteIndex+j]
|
|
||||||
sb.WriteByte('%')
|
|
||||||
// Bitwise operations are inspired by "net/url"
|
|
||||||
sb.WriteByte(upperhex[b>>4])
|
|
||||||
sb.WriteByte(upperhex[b&15])
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return sb.String()
|
|
||||||
}
|
|
||||||
|
|
||||||
// Baggage is a list of baggage members representing the baggage-string as
|
|
||||||
// defined by the W3C Baggage specification.
|
|
||||||
type Baggage struct { //nolint:golint
|
|
||||||
list baggage.List
|
|
||||||
}
|
|
||||||
|
|
||||||
// New returns a new valid Baggage. It returns an error if it results in a
|
|
||||||
// Baggage exceeding limits set in that specification.
|
|
||||||
//
|
|
||||||
// It expects all the provided members to have already been validated.
|
|
||||||
func New(members ...Member) (Baggage, error) {
|
|
||||||
if len(members) == 0 {
|
|
||||||
return Baggage{}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
b := make(baggage.List)
|
|
||||||
for _, m := range members {
|
|
||||||
if !m.hasData {
|
|
||||||
return Baggage{}, errInvalidMember
|
|
||||||
}
|
|
||||||
|
|
||||||
// OpenTelemetry resolves duplicates by last-one-wins.
|
|
||||||
b[m.key] = baggage.Item{
|
|
||||||
Value: m.value,
|
|
||||||
Properties: m.properties.asInternal(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check member numbers after deduplication.
|
|
||||||
if len(b) > maxMembers {
|
|
||||||
return Baggage{}, errMemberNumber
|
|
||||||
}
|
|
||||||
|
|
||||||
bag := Baggage{b}
|
|
||||||
if n := len(bag.String()); n > maxBytesPerBaggageString {
|
|
||||||
return Baggage{}, fmt.Errorf("%w: %d", errBaggageBytes, n)
|
|
||||||
}
|
|
||||||
|
|
||||||
return bag, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Parse attempts to decode a baggage-string from the passed string. It
|
|
||||||
// returns an error if the input is invalid according to the W3C Baggage
|
|
||||||
// specification.
|
|
||||||
//
|
|
||||||
// If there are duplicate list-members contained in baggage, the last one
|
|
||||||
// defined (reading left-to-right) will be the only one kept. This diverges
|
|
||||||
// from the W3C Baggage specification which allows duplicate list-members, but
|
|
||||||
// conforms to the OpenTelemetry Baggage specification.
|
|
||||||
func Parse(bStr string) (Baggage, error) {
|
|
||||||
if bStr == "" {
|
|
||||||
return Baggage{}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
if n := len(bStr); n > maxBytesPerBaggageString {
|
|
||||||
return Baggage{}, fmt.Errorf("%w: %d", errBaggageBytes, n)
|
|
||||||
}
|
|
||||||
|
|
||||||
b := make(baggage.List)
|
|
||||||
for _, memberStr := range strings.Split(bStr, listDelimiter) {
|
|
||||||
m, err := parseMember(memberStr)
|
|
||||||
if err != nil {
|
|
||||||
return Baggage{}, err
|
|
||||||
}
|
|
||||||
// OpenTelemetry resolves duplicates by last-one-wins.
|
|
||||||
b[m.key] = baggage.Item{
|
|
||||||
Value: m.value,
|
|
||||||
Properties: m.properties.asInternal(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// OpenTelemetry does not allow for duplicate list-members, but the W3C
|
|
||||||
// specification does. Now that we have deduplicated, ensure the baggage
|
|
||||||
// does not exceed list-member limits.
|
|
||||||
if len(b) > maxMembers {
|
|
||||||
return Baggage{}, errMemberNumber
|
|
||||||
}
|
|
||||||
|
|
||||||
return Baggage{b}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Member returns the baggage list-member identified by key.
|
|
||||||
//
|
|
||||||
// If there is no list-member matching the passed key the returned Member will
|
|
||||||
// be a zero-value Member.
|
|
||||||
// The returned member is not validated, as we assume the validation happened
|
|
||||||
// when it was added to the Baggage.
|
|
||||||
func (b Baggage) Member(key string) Member {
|
|
||||||
v, ok := b.list[key]
|
|
||||||
if !ok {
|
|
||||||
// We do not need to worry about distinguishing between the situation
|
|
||||||
// where a zero-valued Member is included in the Baggage because a
|
|
||||||
// zero-valued Member is invalid according to the W3C Baggage
|
|
||||||
// specification (it has an empty key).
|
|
||||||
return newInvalidMember()
|
|
||||||
}
|
|
||||||
|
|
||||||
return Member{
|
|
||||||
key: key,
|
|
||||||
value: v.Value,
|
|
||||||
properties: fromInternalProperties(v.Properties),
|
|
||||||
hasData: true,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Members returns all the baggage list-members.
|
|
||||||
// The order of the returned list-members does not have significance.
|
|
||||||
//
|
|
||||||
// The returned members are not validated, as we assume the validation happened
|
|
||||||
// when they were added to the Baggage.
|
|
||||||
func (b Baggage) Members() []Member {
|
|
||||||
if len(b.list) == 0 {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
members := make([]Member, 0, len(b.list))
|
|
||||||
for k, v := range b.list {
|
|
||||||
members = append(members, Member{
|
|
||||||
key: k,
|
|
||||||
value: v.Value,
|
|
||||||
properties: fromInternalProperties(v.Properties),
|
|
||||||
hasData: true,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
return members
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetMember returns a copy the Baggage with the member included. If the
|
|
||||||
// baggage contains a Member with the same key the existing Member is
|
|
||||||
// replaced.
|
|
||||||
//
|
|
||||||
// If member is invalid according to the W3C Baggage specification, an error
|
|
||||||
// is returned with the original Baggage.
|
|
||||||
func (b Baggage) SetMember(member Member) (Baggage, error) {
|
|
||||||
if !member.hasData {
|
|
||||||
return b, errInvalidMember
|
|
||||||
}
|
|
||||||
|
|
||||||
n := len(b.list)
|
|
||||||
if _, ok := b.list[member.key]; !ok {
|
|
||||||
n++
|
|
||||||
}
|
|
||||||
list := make(baggage.List, n)
|
|
||||||
|
|
||||||
for k, v := range b.list {
|
|
||||||
// Do not copy if we are just going to overwrite.
|
|
||||||
if k == member.key {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
list[k] = v
|
|
||||||
}
|
|
||||||
|
|
||||||
list[member.key] = baggage.Item{
|
|
||||||
Value: member.value,
|
|
||||||
Properties: member.properties.asInternal(),
|
|
||||||
}
|
|
||||||
|
|
||||||
return Baggage{list: list}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// DeleteMember returns a copy of the Baggage with the list-member identified
|
|
||||||
// by key removed.
|
|
||||||
func (b Baggage) DeleteMember(key string) Baggage {
|
|
||||||
n := len(b.list)
|
|
||||||
if _, ok := b.list[key]; ok {
|
|
||||||
n--
|
|
||||||
}
|
|
||||||
list := make(baggage.List, n)
|
|
||||||
|
|
||||||
for k, v := range b.list {
|
|
||||||
if k == key {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
list[k] = v
|
|
||||||
}
|
|
||||||
|
|
||||||
return Baggage{list: list}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Len returns the number of list-members in the Baggage.
|
|
||||||
func (b Baggage) Len() int {
|
|
||||||
return len(b.list)
|
|
||||||
}
|
|
||||||
|
|
||||||
// String encodes Baggage into a string compliant with the W3C Baggage
|
|
||||||
// specification. The returned string will be invalid if the Baggage contains
|
|
||||||
// any invalid list-members.
|
|
||||||
func (b Baggage) String() string {
|
|
||||||
members := make([]string, 0, len(b.list))
|
|
||||||
for k, v := range b.list {
|
|
||||||
members = append(members, Member{
|
|
||||||
key: k,
|
|
||||||
value: v.Value,
|
|
||||||
properties: fromInternalProperties(v.Properties),
|
|
||||||
}.String())
|
|
||||||
}
|
|
||||||
return strings.Join(members, listDelimiter)
|
|
||||||
}
|
|
||||||
Loaded 100 of 807 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user