-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrestconf.mbt
More file actions
394 lines (365 loc) · 11.5 KB
/
Copy pathrestconf.mbt
File metadata and controls
394 lines (365 loc) · 11.5 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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
///|
/// Which of go-zero's built-in layers the engine installs (← `MiddlewaresConf`).
/// Every flag defaults to `true`, so an `etc/*.yaml` that says nothing about
/// middleware still gets the whole chain.
pub(all) struct MiddlewaresConf {
trace : Bool
log : Bool
prometheus : Bool
max_conns : Bool
breaker : Bool
shedding : Bool
timeout : Bool
recover : Bool
metrics : Bool
max_bytes : Bool
gunzip : Bool
} derive(Eq, Debug)
///|
/// The full chain, which is what go-zero defaults to.
pub fn MiddlewaresConf::new(
trace? : Bool = true,
log? : Bool = true,
prometheus? : Bool = true,
max_conns? : Bool = true,
breaker? : Bool = true,
shedding? : Bool = true,
timeout? : Bool = true,
recover? : Bool = true,
metrics? : Bool = true,
max_bytes? : Bool = true,
gunzip? : Bool = true,
) -> MiddlewaresConf {
{
trace,
log,
prometheus,
max_conns,
breaker,
shedding,
timeout,
recover,
metrics,
max_bytes,
gunzip,
}
}
///|
/// One signing key the request-signature check would verify against (←
/// `rest.PrivateKeyConf`).
pub(all) struct PrivateKeyConf {
fingerprint : String
key_file : String
} derive(Eq, Debug)
///|
/// Request-signature settings (← `rest.SignatureConf`): whether an unsigned or
/// badly-signed request is refused outright, how long a signature stays valid,
/// and the keys it is checked against.
///
/// moonzero loads and validates this config — a strict service with no keys is
/// refused at assembly, as go-zero's `ErrSignatureConfig` does — but ships no
/// content-signature layer to consume it.
pub(all) struct SignatureConf {
strict : Bool
expiry_ms : Int64
private_keys : Array[PrivateKeyConf]
} derive(Eq, Debug)
///|
/// Signature settings that verify nothing: not strict, go-zero's one-hour
/// expiry, no keys.
pub fn SignatureConf::new(
strict? : Bool = false,
expiry_ms? : Int64 = 3600000L,
private_keys? : Array[PrivateKeyConf] = [],
) -> SignatureConf {
{ strict, expiry_ms, private_keys, }
}
///|
/// A REST service's configuration (← go-zero's `rest.RestConf`), embedding
/// `ServiceConf` the way go-zero's does. The name, bind address and request
/// timeout live on that embedded config — `host()`, `port()` and `timeout_ms()`
/// read them — and everything else here is RestConf's own.
///
/// `max_bytes` is an `Int` where go-zero uses `int64`: it is compared against a
/// request's `Content-Length`, and its own `range=` tag caps it at 32 MiB.
pub(all) struct RestConf {
service : ServiceConf
cert_file : String
key_file : String
verbose : Bool
max_conns : Int
max_bytes : Int
cpu_threshold : Int64
signature : SignatureConf
middlewares : MiddlewaresConf
trace_ignore_paths : Array[String]
}
///|
/// A REST config with go-zero's defaults: no TLS, not verbose, 10000 connections,
/// a 1 MiB body cap, a 90% CPU shed threshold, and the full middleware chain.
pub fn RestConf::new(
service? : ServiceConf = ServiceConf::new(),
cert_file? : String = "",
key_file? : String = "",
verbose? : Bool = false,
max_conns? : Int = 10000,
max_bytes? : Int = 1048576,
cpu_threshold? : Int64 = 900L,
signature? : SignatureConf = SignatureConf::new(),
middlewares? : MiddlewaresConf = MiddlewaresConf::new(),
trace_ignore_paths? : Array[String] = [],
) -> RestConf {
{
service,
cert_file,
key_file,
verbose,
max_conns,
max_bytes,
cpu_threshold,
signature,
middlewares,
trace_ignore_paths,
}
}
///|
/// The address the service binds.
pub fn RestConf::host(self : RestConf) -> String {
self.service.host
}
///|
/// The port the service binds.
pub fn RestConf::port(self : RestConf) -> Int {
self.service.port
}
///|
/// The per-request timeout budget in milliseconds; `0` disables it.
pub fn RestConf::timeout_ms(self : RestConf) -> Int {
self.service.timeout_ms
}
///|
/// Whether TLS is configured — go-zero serves HTTPS once both files are named.
pub fn RestConf::tls(self : RestConf) -> Bool {
self.cert_file.length() > 0 && self.key_file.length() > 0
}
///|
/// Load a `RestConf` from the YAML go-zero ships as `etc/*.yaml`. Keys are
/// matched canonically, `MOONZERO_*` env variables override the file, and a value
/// outside its `options=`/`range=` constraint is an error.
///
/// `Name` and `Port` carry no default, exactly as in go-zero: a rest service that
/// does not say who it is or where to listen fails to load.
pub fn RestConf::from_yaml(src : String) -> RestConf raise ConfigError {
rest_conf_of(Conf::of_yaml(src))
}
///|
/// Load a `RestConf` from a JSON config string, with the same semantics as
/// `from_yaml`.
pub fn RestConf::from_json(src : String) -> RestConf raise ConfigError {
rest_conf_of(Conf::of_json(src))
}
///|
/// Decode a `RestConf` from a loaded document.
fn rest_conf_of(c : Conf) -> RestConf raise ConfigError {
let def = RestConf::new()
{
service: service_conf_of(c),
cert_file: c.string("CertFile", default=def.cert_file),
key_file: c.string("KeyFile", default=def.key_file),
verbose: c.bool("Verbose", default=def.verbose),
max_conns: c.int("MaxConns", default=def.max_conns),
max_bytes: c.int("MaxBytes", default=def.max_bytes, range="[0:33554432]"),
cpu_threshold: c.int64(
"CpuThreshold",
default=def.cpu_threshold,
range="[0:1000]",
),
signature: signature_of(c),
middlewares: middlewares_of(c),
trace_ignore_paths: c.strings(
"TraceIgnorePaths",
default=def.trace_ignore_paths,
),
}
}
///|
/// Decode the `Signature` block.
fn signature_of(c : Conf) -> SignatureConf raise ConfigError {
let def = SignatureConf::new()
let keys : Array[PrivateKeyConf] = []
for k in c.list("Signature.PrivateKeys") {
keys.push({
fingerprint: k.string("Fingerprint", default=""),
key_file: k.string("KeyFile", default=""),
})
}
{
strict: c.bool("Signature.Strict", default=def.strict),
expiry_ms: c.int64("Signature.Expiry", default=def.expiry_ms),
private_keys: keys,
}
}
///|
/// Decode the `Middlewares` block.
fn middlewares_of(c : Conf) -> MiddlewaresConf raise ConfigError {
{
trace: c.bool("Middlewares.Trace", default=true),
log: c.bool("Middlewares.Log", default=true),
prometheus: c.bool("Middlewares.Prometheus", default=true),
max_conns: c.bool("Middlewares.MaxConns", default=true),
breaker: c.bool("Middlewares.Breaker", default=true),
shedding: c.bool("Middlewares.Shedding", default=true),
timeout: c.bool("Middlewares.Timeout", default=true),
recover: c.bool("Middlewares.Recover", default=true),
metrics: c.bool("Middlewares.Metrics", default=true),
max_bytes: c.bool("Middlewares.MaxBytes", default=true),
gunzip: c.bool("Middlewares.Gunzip", default=true),
}
}
///|
/// One layer of the assembled chain: go-zero's name for the handler, and the
/// middleware that stands in for it.
pub(all) struct Layer {
name : String
middleware : Middleware
}
///|
/// The engine that turns a `RestConf` into a runnable service (← go-zero's
/// `rest.engine`). It owns the state the built-in layers need — the connection
/// permits, the breaker window, the metric set, the shedder — so every request
/// shares one of each, and it installs exactly the layers `Middlewares` asks for.
pub struct RestEngine {
conf : RestConf
clock : Clock
logger : Logger
metrics : ServerMetrics
conns : MaxConns
circuit : Breaker
shedder : Shedder
}
///|
/// Build the engine for `conf`, pointing the logger at the configured level (←
/// `ServiceConf.SetUp`'s `logx.SetUp`).
///
/// `usage` is the CPU meter the shedder reads, per mille. Raises `ConfigError`
/// for a strict signature config with no keys, which is go-zero's
/// `ErrSignatureConfig`.
pub fn RestEngine::new(
conf : RestConf,
clock? : Clock = Clock::system(),
logger? : Logger,
metrics? : ServerMetrics = ServerMetrics::new(),
usage? : () -> Int64,
) -> RestEngine raise ConfigError {
if conf.signature.strict && conf.signature.private_keys.length() == 0 {
raise ConfigError("signature is strict but no private keys are configured")
}
let logger = logger.unwrap_or(logx)
logger.set_level(conf.service.log_level)
{
conf,
clock,
logger,
metrics,
conns: MaxConns::new(conf.max_conns),
circuit: Breaker::new(clock),
shedder: Shedder::new(conf.cpu_threshold, usage?),
}
}
///|
/// The config the engine was built from.
pub fn RestEngine::conf(self : RestEngine) -> RestConf {
self.conf
}
///|
/// The metric set the `prometheus` layer records into — the same one
/// `mount_metrics` publishes.
pub fn RestEngine::metrics(self : RestEngine) -> ServerMetrics {
self.metrics
}
///|
/// The chain the flags ask for, outermost first, in go-zero's
/// `buildChainWithNativeMiddlewares` order.
///
/// A layer whose configured value disables it is left out even when its flag is
/// on, as in go-zero: no shedder without a `CpuThreshold`, no timeout without a
/// budget, no body cap without a `MaxBytes`.
///
/// Two of go-zero's eleven flags install nothing here. `Metrics` is go-zero's
/// internal `stat.Metrics` sink, which moonzero has no counterpart for — its one
/// metric set is the Prometheus one the `Prometheus` flag installs. `Gunzip`
/// needs a DEFLATE decoder, which neither moonzero nor any dependency carries.
/// Both flags still load, so a go-zero config round-trips through `RestConf`.
pub fn RestEngine::layers(self : RestEngine) -> Array[Layer] {
let mw = self.conf.middlewares
let out : Array[Layer] = []
if mw.trace {
out.push({
name: "trace",
middleware: tracing(ignore_paths=self.conf.trace_ignore_paths),
})
}
if mw.log {
out.push({
name: "log",
middleware: structured_logging(self.clock, logger=self.logger),
})
}
if mw.prometheus {
out.push({
name: "prometheus",
middleware: metrics(self.metrics, self.clock),
})
}
if mw.max_conns && self.conf.max_conns > 0 {
out.push({ name: "maxConns", middleware: max_conns(self.conns), })
}
if mw.breaker {
out.push({ name: "breaker", middleware: breaker(self.circuit), })
}
if mw.shedding && self.conf.cpu_threshold > 0L {
out.push({ name: "shedding", middleware: shedding(self.shedder), })
}
if mw.timeout && self.conf.service.timeout_ms > 0 {
out.push({
name: "timeout",
middleware: timeout(self.conf.service.timeout_ms.to_int64(), self.clock),
})
}
if mw.recover {
out.push({ name: "recover", middleware: inner => recovery(inner), })
}
if mw.max_bytes && self.conf.max_bytes > 0 {
out.push({ name: "maxBytes", middleware: maxbytes(self.conf.max_bytes), })
}
out
}
///|
/// The names of the layers `layers` would install, outermost first.
pub fn RestEngine::names(self : RestEngine) -> Array[String] {
self.layers().map(l => l.name)
}
///|
/// Assemble `app` under the configured chain. go-zero's `chain.New` names the
/// outermost handler first while `Server::use_` makes the most recent layer
/// outermost, so the list goes on back to front.
pub fn RestEngine::build(self : RestEngine, app : @moonapi.App) -> Server {
let layers = self.layers()
let mut server = Server::new(self.conf.service, app)
for i = layers.length() - 1; i >= 0; i = i - 1 {
server = server.use_(layers[i].middleware)
}
server
}
///|
pub extend MiddlewaresConf with Debug::{to_repr}
///|
pub extend MiddlewaresConf with Eq::{not_equal, equal}
///|
pub extend PrivateKeyConf with Debug::{to_repr}
///|
pub extend PrivateKeyConf with Eq::{not_equal, equal}
///|
pub extend SignatureConf with Debug::{to_repr}
///|
pub extend SignatureConf with Eq::{not_equal, equal}