Repository navigation
Expand file tree
/
Copy pathconfig.go
More file actions
271 lines (229 loc) · 14.9 KB
/
Copy pathconfig.go
File metadata and controls
271 lines (229 loc) · 14.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
package peerdb
import (
"context"
"github.com/alecthomas/kong"
mapset "github.com/deckarep/golang-set/v2"
"gitlab.com/tozd/go/cli"
"gitlab.com/tozd/go/errors"
"gitlab.com/tozd/go/zerolog"
"gitlab.com/tozd/waf"
internalSite "gitlab.com/peerdb/peerdb/internal/site"
)
const (
// DefaultListen is the default TCP listen address.
DefaultListen = ":8080"
// DefaultProxyTo is the default URL to proxy to during development.
DefaultProxyTo = "http://localhost:5173"
// DefaultElastic is the default Elasticsearch URL.
DefaultElastic = "http://127.0.0.1:9200"
// DefaultSchema is the default database schema name.
DefaultSchema = internalSite.DefaultSchema
// DefaultIndexPrefix is the default Elasticsearch index prefix. The visibility level name is appended to it to form each per-level index name.
DefaultIndexPrefix = internalSite.DefaultIndexPrefix
// DefaultShards is the default number of Elasticsearch shards.
DefaultShards = "10"
// DefaultTitle is the default application title.
DefaultTitle = internalSite.DefaultTitle
// DefaultTestData is the default directory with the test data set. It is empty, so populate inserts only the core documents unless a directory is passed.
// An application built on PeerDB which ships a test data set of its own passes the directory it keeps it in instead.
DefaultTestData = ""
)
// PostgresConfig contains configuration for PostgreSQL database connection.
//
//nolint:lll
type PostgresConfig struct {
URL kong.FileContentFlag ` env:"URL_PATH" help:"File with PostgreSQL database URL." placeholder:"PATH" required:"" short:"d" yaml:"database"`
Schema string `default:"${defaultSchema}" help:"Name of PostgreSQL schema to use when sites are not configured." placeholder:"NAME" yaml:"schema"`
}
// ElasticConfig contains configuration for ElasticSearch connection.
//
//nolint:lll
type ElasticConfig struct {
URL string `default:"${defaultElastic}" help:"URL of the ElasticSearch instance." placeholder:"URL" short:"e" yaml:"elastic"`
IndexPrefix string `default:"${defaultIndexPrefix}" help:"Prefix of ElasticSearch index names to use when sites are not configured." placeholder:"PREFIX" yaml:"indexPrefix"`
Shards int `default:"${defaultShards}" help:"Number of ElasticSearch shards when initializing indices." placeholder:"NUM" yaml:"shards"`
}
// StorageConfig contains configuration for file storage.
type StorageConfig struct {
Dir string `help:"Directory under which to store files." placeholder:"PATH" required:"" short:"S" type:"path" yaml:"dir"`
}
// Customizer allows a consumer using PeerDB as a library to attach code at well-defined points of the
// lifecycle, uniformly across all commands, so that commands cannot diverge in how sites are configured.
// All hooks are optional. Set it on Globals in code before command-line parsing.
type Customizer struct {
// SiteDefaults is called for every site after the configuration file and command-line flags have been
// applied, after PeerDB has filled its own defaults into some fields the configuration left unset, and
// before the site is validated. It can keep, extend, replace, or unset those defaults, fill defaults
// into further fields the configuration left unset (the configuration can then override such fields),
// or overwrite fields unconditionally (such fields are fixed by code and the configuration cannot change
// them). SiteDefaults is also called for sites synthesized when none are configured (the default site and
// the domain/certificate-based sites), and can run more than once for the same site, so it must be
// idempotent and accept values it has set itself.
SiteDefaults func(site *Site) errors.E
// ConfigureBase is called for every site right after Init has populated site.Base and before the base
// is started, in every command which initializes the base. It is the place to register document, file,
// and indexing hooks on the base. It is called exactly once per site.
ConfigureBase func(site *Site) errors.E
}
// applySiteDefaults fills PeerDB defaults into site fields the configuration left unset and then calls
// the consumer's SiteDefaults customizer (when set), so the customizer always observes the defaults
// already applied and can keep, extend, replace, or unset them. Only fields whose customizer operation
// is extending or overriding the default are filled with defaults first. Fields a customizer may want to
// default itself stay unset here, so the customizer can see whether the configuration set them; they are
// defaulted during validation, which runs after the customizer. Both the defaulting and (per its
// contract) the customizer are idempotent, so this can run more than once for the same site.
func applySiteDefaults(customize Customizer, site *Site) errors.E {
if site.Features.HiddenFacetProperties == nil {
// This also makes a new slice, so it is safe to mutate it in SiteDefaults.
site.Features.HiddenFacetProperties = internalSite.DefaultHiddenFacetProperties()
}
if customize.SiteDefaults != nil {
return customize.SiteDefaults(site)
}
return nil
}
// Globals describes top-level (global) flags.
type Globals struct {
zerolog.LoggingConfig `yaml:",inline"`
Version kong.VersionFlag `help:"Show program's version and exit." short:"V" yaml:"-"`
Config cli.ConfigFlag `help:"Load configuration from a JSON or YAML file." name:"config" placeholder:"PATH" short:"c" yaml:"-"`
Postgres PostgresConfig `embed:"" envprefix:"POSTGRES_" prefix:"postgres." yaml:"postgres"`
Elastic ElasticConfig `embed:"" envprefix:"ELASTIC_" prefix:"elastic." yaml:"elastic"`
Storage StorageConfig `embed:"" envprefix:"STORAGE_" prefix:"storage." yaml:"storage"`
Sites []internalSite.Site `help:"Site configuration as JSON or YAML. Can be provided multiple times." name:"site" placeholder:"SITE" sep:"none" short:"s" yaml:"sites"`
// Customize is set in code by a consumer using PeerDB as a library. It is not part of the configuration.
Customize Customizer `json:"-" kong:"-" yaml:"-"`
}
// Validate validates the global configuration.
func (g *Globals) Validate() error {
domains := mapset.NewThreadUnsafeSet[string]()
for i, site := range g.Sites {
// This is not validated when Site is not populated by Kong.
if site.Domain == "" {
errE := errors.New("domain is required for site")
errors.Details(errE)["site"] = i
return errE
}
// Defaults and the consumer customizer run before validation, so that the customizer sees Roles
// and Visibility in their raw configured state (e.g. an empty Visibility is still empty, not yet
// defaulted by validation) and so that the values it sets are validated.
errE := applySiteDefaults(g.Customize, &site)
if errE != nil {
return errE
}
// To make sure validation is called.
err := site.Validate()
if err != nil {
return errors.WithStack(err)
}
if !domains.Add(site.Domain) {
errE := errors.New("duplicate site for domain")
errors.Details(errE)["domain"] = site.Domain
return errE
}
// Site might have been changed, so we assign it back.
g.Sites[i] = site
}
return nil
}
// Config provides configuration.
// It is used as configuration for Kong command-line parser as well.
type Config struct {
Globals `yaml:"globals"`
Serve ServeCommand `cmd:"" default:"withargs" help:"Run HTTP server. Default command." yaml:"serve"`
Populate PopulateCommand `cmd:"" help:"Populate database with documents." yaml:"populate"`
DB DBCommand `cmd:"" help:"Manage database." yaml:"db"`
}
// ServeCommand contains configuration for the serve command.
//
//nolint:lll
type ServeCommand struct {
Server waf.Server[*internalSite.Site] `embed:"" yaml:",inline"`
Username string ` help:"Require authentication to access all sites. Its username." yaml:"username"`
Password kong.FileContentFlag `env:"PASSWORD_PATH" help:"Require authentication to access all sites. Its password." placeholder:"PATH" yaml:"password"`
Domain string ` group:"Let's Encrypt:" help:"Domain name to request for Let's Encrypt's certificate when sites are not configured." name:"tls.domain" placeholder:"STRING" yaml:"domain"`
Title string `default:"${defaultTitle}" help:"Title to be shown to the users when sites are not configured." placeholder:"STRING" short:"T" yaml:"title"`
// AfterInit is set in code by a consumer using PeerDB as a library. It is called at the end of Init,
// after the service has been created and the sites' bases initialized, and before Prepare starts
// them, so it can wrap the service, add routes, and register service-scoped river workers (the river
// clients are not yet started). It is not part of the configuration.
AfterInit func(ctx context.Context, service *Service) errors.E `json:"-" kong:"-" yaml:"-"`
// AfterPrepare is set in code by a consumer using PeerDB as a library. It is called at the end of
// Prepare, after the sites' bases have been started (the river clients are running) and before the
// request handler is constructed, so it can e.g. register periodic river jobs. It is not part of the
// configuration.
AfterPrepare func(ctx context.Context, service *Service) errors.E `json:"-" kong:"-" yaml:"-"`
}
// Validate validates the serve command configuration.
func (c *ServeCommand) Validate() error {
// We have to call Validate on kong-embedded structs ourselves.
// See: https://github.com/alecthomas/kong/issues/90
err := c.Server.HTTPS.Validate()
if err != nil {
return errors.WithStack(err)
}
if c.Domain != "" && c.Server.HTTPS.LetsEncryptCache == "" {
return errors.New("Let's Encrypt's cache directory is required for Let's Encrypt's certificate")
}
if (c.Username != "" && c.Password == nil) || (c.Username == "" && c.Password != nil) {
return errors.New("both username and password have to be set to require authentication, or neither")
}
return nil
}
// PopulateCommand contains configuration for the populate command.
//
//nolint:lll
type PopulateCommand struct {
SaveDir string ` help:"Save intermediate structs as files into a directory." name:"save" placeholder:"DIR" type:"path" yaml:"saveDir"`
OutputDir string ` help:"Save documents as files into a directory." name:"output" placeholder:"DIR" short:"O" type:"path" yaml:"outputDir"`
TestDataDir string `default:"${defaultTestData}" help:"Path to directory with test data to load. Pass an empty value to not load test data." name:"test-data" placeholder:"DIR" short:"T" type:"path" yaml:"testDataDir"`
DryRun bool ` help:"Dry run. Do everything but insert documents into the database." yaml:"dryRun"`
// PopulateSite is set in code by a consumer using PeerDB as a library to replace how a site is
// populated. When nil, core documents are generated and inserted. It is called with a per-site
// cancellable context whose logger carries the site's indexPrefix and schema fields and whose
// fallback database context is set. It returns the shutdown function from PopulateAndStart (or nil
// when the base was not started). Run cancels the context and then runs the shutdown. It is not
// part of the configuration.
PopulateSite func(ctx context.Context, site Site) (func(), errors.E) `json:"-" kong:"-" yaml:"-"`
}
// DBWaitCommand waits for pending indexing to complete.
type DBWaitCommand struct{}
// DBReindexCommand forces a full reindex of all documents.
//
//nolint:lll
type DBReindexCommand struct {
RecreateIndex bool `help:"Delete and recreate the ElasticSearch indices before reindexing, so the current mapping is applied." name:"recreate-index" yaml:"recreateIndex"`
}
// DBRepairCommand repairs the database based on stored documents.
type DBRepairCommand struct {
DryRun bool `help:"Dry run. Do not change anything. Only report what would be repaired." name:"dry-run" yaml:"dryRun"`
}
// DBVacuumCommand reclaims dead tuples in PostgreSQL and expunges deleted documents from ElasticSearch for all sites.
type DBVacuumCommand struct{}
// DBWipeCommand drops PostgreSQL schemas and deletes ElasticSearch indices for all sites, and clears
// the storage directory holding file contents.
type DBWipeCommand struct{}
// DBExportCommand exports documents to CSV, JSON, or struct.
//
//nolint:lll
type DBExportCommand struct {
Output string `default:"-" help:"Output file path. Use - for stdout." placeholder:"PATH" short:"o" type:"path" yaml:"output"`
Format string `default:"csv" enum:"csv,json,struct" help:"Output format." placeholder:"FORMAT" short:"f" yaml:"format"`
InstanceOf []string ` help:"Limit to instances of class (mnemonic or ID)." name:"instance-of" placeholder:"STRING" short:"i" yaml:"instanceOf"`
Property []string ` help:"Properties to export (a.b.c path, * for single-level wildcard, ** for recursive)." name:"property" placeholder:"STRING" short:"p" yaml:"property"`
}
// DBDiagramCommand outputs a Mermaid ER diagram of classes and fields.
type DBDiagramCommand struct {
Output string `default:"-" help:"Output file path. Use - for stdout." placeholder:"PATH" short:"o" type:"path" yaml:"output"`
SkipCore bool ` help:"Exclude core entities and INSTANCE_OF references to them." name:"skip-core" yaml:"skipCore"`
}
// DBCommand contains sub-commands for managing database.
type DBCommand struct {
Wait DBWaitCommand `cmd:"" help:"Wait for pending indexing to complete and exit." yaml:"wait"`
Reindex DBReindexCommand `cmd:"" help:"Force full reindex of all documents." yaml:"reindex"`
Repair DBRepairCommand `cmd:"" help:"Repair database based on stored documents." yaml:"repair"`
Vacuum DBVacuumCommand `cmd:"" help:"Vacuum PostgreSQL and expunge ElasticSearch deletes." yaml:"vacuum"`
Wipe DBWipeCommand `cmd:"" help:"Wipe PostgreSQL schemas, ElasticSearch indices, and storage directory." yaml:"wipe"`
Export DBExportCommand `cmd:"" help:"Export documents to CSV, JSON, or struct." yaml:"export"`
Diagram DBDiagramCommand `cmd:"" help:"Output Mermaid ER diagram of classes and fields." yaml:"diagram"`
}