Antonio Mika
·
2025-03-12
config.go
1package pgs
2
3import (
4 "fmt"
5 "log/slog"
6 "path/filepath"
7 "time"
8
9 pgsdb "github.com/picosh/pico/pkg/apps/pgs/db"
10 "github.com/picosh/pico/pkg/shared/storage"
11 "github.com/picosh/utils"
12)
13
14type PgsConfig struct {
15 CacheControl string
16 CacheTTL time.Duration
17 Domain string
18 MaxAssetSize int64
19 MaxSize uint64
20 MaxSpecialFileSize int64
21 SshHost string
22 SshPort string
23 StorageDir string
24 TxtPrefix string
25 WebPort string
26 WebProtocol string
27
28 // This channel will receive the surrogate key for a project (e.g. static site)
29 // which will inform the caching layer to clear the cache for that site.
30 CacheClearingQueue chan string
31 // Database layer; it's just an interface that could be implemented
32 // with anything.
33 DB pgsdb.PgsDB
34 Logger *slog.Logger
35 // Where we store the static assets uploaded to our service.
36 Storage storage.StorageServe
37}
38
39func (c *PgsConfig) AssetURL(username, projectName, fpath string) string {
40 if username == projectName {
41 return fmt.Sprintf(
42 "%s://%s.%s/%s",
43 c.WebProtocol,
44 username,
45 c.Domain,
46 fpath,
47 )
48 }
49
50 return fmt.Sprintf(
51 "%s://%s-%s.%s/%s",
52 c.WebProtocol,
53 username,
54 projectName,
55 c.Domain,
56 fpath,
57 )
58}
59
60func (c *PgsConfig) StaticPath(fname string) string {
61 return filepath.Join("pgs", fname)
62}
63
64var maxSize = uint64(25 * utils.MB)
65var maxAssetSize = int64(10 * utils.MB)
66
67// Needs to be small for caching files like _headers and _redirects.
68var maxSpecialFileSize = int64(5 * utils.KB)
69
70func NewPgsConfig(logger *slog.Logger, dbpool pgsdb.PgsDB, st storage.StorageServe) *PgsConfig {
71 domain := utils.GetEnv("PGS_DOMAIN", "pgs.sh")
72 port := utils.GetEnv("PGS_WEB_PORT", "3000")
73 protocol := utils.GetEnv("PGS_PROTOCOL", "https")
74 storageDir := utils.GetEnv("PGS_STORAGE_DIR", ".storage")
75 cacheTTL, err := time.ParseDuration(utils.GetEnv("PGS_CACHE_TTL", ""))
76 if err != nil {
77 cacheTTL = 600 * time.Second
78 }
79 cacheControl := utils.GetEnv(
80 "PGS_CACHE_CONTROL",
81 fmt.Sprintf("max-age=%d", int(cacheTTL.Seconds())))
82
83 sshHost := utils.GetEnv("PGS_SSH_HOST", "0.0.0.0")
84 sshPort := utils.GetEnv("PGS_SSH_PORT", "2222")
85
86 cfg := PgsConfig{
87 CacheControl: cacheControl,
88 CacheTTL: cacheTTL,
89 Domain: domain,
90 MaxAssetSize: maxAssetSize,
91 MaxSize: maxSize,
92 MaxSpecialFileSize: maxSpecialFileSize,
93 SshHost: sshHost,
94 SshPort: sshPort,
95 StorageDir: storageDir,
96 TxtPrefix: "pgs",
97 WebPort: port,
98 WebProtocol: protocol,
99
100 CacheClearingQueue: make(chan string, 100),
101 DB: dbpool,
102 Logger: logger,
103 Storage: st,
104 }
105
106 return &cfg
107}