summaryrefslogtreecommitdiff
path: root/src/gobang.go
blob: 877724735211fb08ef6fc82e3a546e6bd6449ec6 (plain) (blame)
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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
package gobang

import (
	"cmp"
	"crypto/rand"
	"errors"
	"fmt"
	"io"
	"log/slog"
	"math/big"
	"os"
	"reflect"
	"regexp"
	"runtime"
	"runtime/debug"
	"slices"
	"strings"
	"time"

	"uuid"
)



type LogLevel int8
const (
	 LogLevel_None    LogLevel = 0
	 LogLevel_Error   LogLevel = 1
	 LogLevel_Warning LogLevel = 2
	 LogLevel_Info    LogLevel = 3
	 LogLevel_Debug   LogLevel = 4
)


type SetT[T comparable] struct{
	data map[T]struct{}
}

type PairT[A any, B any] struct{
	L A
	R B
}

type Gauge struct {
	Inc func(...any)
	Dec func(...any)
}

type CopyResult struct {
	Written int64
	Err     error
	Label   string
}



const (
	SQLiteNow = "strftime('%Y-%m-%dT%H:%M:%f000000Z', 'now')"
)


var (
	level LogLevel = LogLevel_Info
	emitMetric = true
	hostname string

	testOutput io.Writer = os.Stderr
	testExitFn  = os.Exit
	exitFn      = os.Exit
	randomReader = rand.Reader

	SourceInfoSkip = 3

	ErrBadSQLTablePrefix = errors.New("Invalid table prefix")
)



func SetOf[T comparable](values ...T) SetT[T] {
	s := SetT[T]{
		data: map[T]struct{}{
		},
	}

	for _, value := range values {
		s.data[value] = struct{}{}
	}

	return s
}

func Contains[T comparable](set SetT[T], value T) bool {
	_, ok := set.data[value]
	return ok
}

func MapIndexed[A any, B any](fn func(A, int) B, coll []A) []B {
	out := make([]B, len(coll))
	for i, x := range coll {
		out[i] = fn(x, i)
	}
	return out
}

func Map[A any, B any](fn func(A) B, coll []A) []B {
	return MapIndexed(func(x A, _ int) B {
		return fn(x)
	}, coll)
}

func Filter[A any](fn func(A) bool, coll []A) []A {
	out := []A{}
	for _, x := range coll {
		if fn(x) {
			out = append(out, x)
		}
	}
	return out
}

func ExitIf(rc int) {
	if rc != 0 {
		exitFn(rc)
	}
}

func PanicIf(err error) {
	if err != nil {
		panic(err)
	}
}

func Must[T any](x T, err error) T {
	PanicIf(err)
	return x
}

func Clamp[T cmp.Ordered](n T, minimum T, maximum T) T {
	return min(maximum, max(minimum, n))
}

var _SQLTablePrefixRE = regexp.MustCompilePOSIX("^[a-zA-Z][_a-zA-z0-9]*$")
func ValidateSQLTablePrefix(prefix string) error {
	if !_SQLTablePrefixRE.MatchString(prefix) {
		return ErrBadSQLTablePrefix
	}

	return nil
}

func WrapErrors(errs ...error) error {
	slices.Reverse(errs)
	var out error
	for _, err := range errs {
		if err != nil {
			if out == nil {
				out = err
			} else {
				out = fmt.Errorf(
					"error %w on top of %w",
					err,
					out,
				)
			}
		}
	}
	return out
}

func SomeError(errs ...error) error {
	for _, err := range errs {
		if err != nil {
			return err
		}
	}
	return nil
}

func SomeFnError(fns ...func() error) error {
	errs := make([]error, len(fns))
	for i, fn := range fns {
		if fn != nil {
			errs[i] = fn()
		}
	}
	return SomeError(errs...)
}

func Random(length int) ([]byte, error) {
	buffer := make([]byte, length)
	_, err := io.ReadFull(randomReader, buffer)
	if err != nil {
		return nil, err
	}
	return buffer, nil
}

func sourceInfo(skip int) slog.Attr {
	pc := make([]uintptr, 10)
	n := runtime.Callers(skip, pc)
	if n == 0 {
		return slog.Group(
			"src",
			"file",     "UNAVAILABLE",
			"function", "UNAVAILABLE",
			"line",     "UNAVAILABLE",
		)
	}

	pc = pc[:n]
	frames := runtime.CallersFrames(pc)
	frame, _ := frames.Next()
	return slog.Group(
		"src",
		"file",     frame.File,
		"function", frame.Function,
		"line",     frame.Line,
	)
}

func logArgs(type_ string) []string {
	return []string {
		"id",    uuid.New().String(),
		"kind",  "log",
		"type",  type_,
	}
}

func anyArr[S ~[]E, E any](arr S) []any {
	ret := make([]any, len(arr))
	for i , el := range arr {
		ret[i] = el
	}
	return ret
}

func Debug(message string, type_ string, args ...any) {
	if level < LogLevel_Debug {
		return
	}

	slog.Debug(
		message,
		slices.Concat(
			anyArr(logArgs(type_)),
			[]any { sourceInfo(SourceInfoSkip) },
			args,
		)...,
	)
}

func Info(message string, type_ string, args ...any) {
	if level < LogLevel_Info {
		return
	}

	slog.Info(
		message,
		slices.Concat(
			anyArr(logArgs(type_)),
			[]any { sourceInfo(SourceInfoSkip) },
			args,
		)...,
	)
}

func Warning(message string, type_ string, args ...any) {
	if level < LogLevel_Warning {
		return
	}

	slog.Warn(
		message,
		slices.Concat(
			anyArr(logArgs(type_)),
			[]any { sourceInfo(SourceInfoSkip) },
			args,
		)...,
	)
}

func Error(message string, type_ string, args ...any) {
	if level < LogLevel_Error {
		return
	}

	slog.Error(
		message,
		slices.Concat(
			anyArr(logArgs(type_)),
			[]any { sourceInfo(SourceInfoSkip) },
			args,
		)...,
	)
}

func metric(type_ string, label string, args ...any) {
	if !emitMetric {
		return
	}

	slog.Info(
		"_",
		slices.Concat(
			[]any {
				"id",    uuid.New().String(),
				"kind",  "metric",
				"type",  type_,
				"label", label,
			},
			[]any { sourceInfo(SourceInfoSkip) },
			args,
		)...,
	)
}

func Timed(label string, thunk func(), args ...any) {
	var (
		start time.Time
		end   time.Time
	)


	{
		start = time.Now()
		thunk()
		end   = time.Now()
	}

	duration  := end.Sub(start)
	metric(
		"timer", label,
		slices.Concat(
			[]any{
				"start", start,
				"end", end,
				"duration", duration,
			},
			args,
		)...,
	)
}

func MakeCounter(label string, staticArgs ...any) func(...any) {
	return func(dynamicArgs ...any) {
		metric(
			"counter", label,
			slices.Concat(
				[]any { "value", 1 },
				staticArgs,
				dynamicArgs,
			)...,
		)
	}
}

func MakeGauge(label string, staticArgs ...any) Gauge {
	var zero = big.NewInt(0)
	var one  = big.NewInt(1)
	count   := big.NewInt(0)
	emitGauge := func(dynamicArgs ...any) {
		if count.Cmp(zero) == -1 {
			Error(
				"Gauge went negative",
				"process-metric",
				slices.Concat(
					[]any { "value", count },
					staticArgs,
					dynamicArgs,
				)...,
			)
			return  // avoid wrong metrics being emitted
		}
		metric(
			"gauge", label,
			slices.Concat(
				[]any { "value", count },
				staticArgs,
				dynamicArgs,
			)...,
		)
	}
	return Gauge {
		Inc: func(dynamicArgs ...any) {
			count.Add(count, one)
			emitGauge(dynamicArgs...)
		},
		Dec: func(dynamicArgs ...any) {
			count.Sub(count, one)
			emitGauge(dynamicArgs...)
		},
	}
}

func showColour() bool {
	return os.Getenv("NO_COLOUR") == ""
}

func TestStart(name string) {
	fmt.Fprintf(testOutput, "%s:\n", name)
}

func Testing(message string, body func()) {
	if showColour() {
		fmt.Fprintf(
			testOutput,
			"\033[0;33mtesting\033[0m: %s... ",
			message,
		)
		body()
		fmt.Fprint(testOutput, "\033[0;32mOK\033[0m.\n")
	} else {
		fmt.Fprintf(testOutput, "testing: %s...", message)
		body()
		fmt.Fprint(testOutput, " OK.\n")
	}
}

func terr() {
	if showColour() {
		fmt.Fprintf(testOutput, "\033[0;31mERR\033[0m")
	} else {
		fmt.Fprintf(testOutput, "ERR")
	}

	_, file, line, ok := runtime.Caller(2)
	if ok {
		fmt.Fprintf(testOutput, " (%s:%d)", file, line)
	}

	fmt.Fprintf(testOutput, ".\n")
}

func TAssertEqual(given any, expected any) {
	if !reflect.DeepEqual(given, expected) {
		terr()
		fmt.Fprintf(testOutput, "given != expected\n")
		fmt.Fprintf(testOutput, "given:    %#v\n", given)
		fmt.Fprintf(testOutput, "expected: %#v\n", expected)
		testExitFn(100)
	}
}

func TAssertEqualS(given any, expected any, message string) {
	if !reflect.DeepEqual(given, expected) {
		terr()
		fmt.Fprintf(testOutput, "message: %s\n", message)
		fmt.Fprintf(testOutput, "given != expected\n")
		fmt.Fprintf(testOutput, "given:    %#v\n", given)
		fmt.Fprintf(testOutput, "expected: %#v\n", expected)
		testExitFn(100)
	}
}

func TAssertEqualI[T any](givenarr []T, expectedarr []T) {
	givenlen    := len(givenarr)
	expectedlen := len(expectedarr)

	if givenlen < expectedlen {
		terr()
		fmt.Fprintf(
			testOutput,
			"expected has %d more elements:\n%#v\n",
			expectedlen - givenlen,
			expectedarr[givenlen:],
		)
		testExitFn(100)
		return
	}

	if givenlen > expectedlen {
		terr()
		fmt.Fprintf(
			testOutput,
			"given has %d more elements:\n%#v\n",
			givenlen - expectedlen,
			givenarr[expectedlen:],
		)
		testExitFn(100)
		return
	}

	for i, _ := range givenarr {
		given    := givenarr[i]
		expected := expectedarr[i]
		if !reflect.DeepEqual(given, expected) {
			terr()
			fmt.Fprintf(
				testOutput,
				"given != expected (i = %d)\n",
				i,
			)
			fmt.Fprintf(testOutput, "given:    %#v\n", given)
			fmt.Fprintf(testOutput, "expected: %#v\n", expected)
			testExitFn(100)
		}
	}
}

func TErrorIf(err error) {
	if err != nil {
		terr()
		fmt.Fprintf(testOutput, "Unexpected error: %#v\n", err)
		testExitFn(100)
	}
}

func TErrorNil(err error) {
	if err == nil {
		terr()
		fmt.Fprintf(testOutput, "Expected error, got nil\n")
		testExitFn(100)
	}
}

func TMust[T any](x T, err error) T {
	TErrorIf(err)
	return x
}

var unfilteringLevel = new(slog.LevelVar)
func SetLoggerOutput(w io.Writer, args ...any) {
	unfilteringLevel.Set(slog.LevelDebug)
	slog.SetDefault(slog.New(slog.NewJSONHandler(w, &slog.HandlerOptions {
		Level: unfilteringLevel,
	})).With(
		slog.Group(
			"info",
			"pid",   os.Getpid(),
			"ppid",  os.Getppid(),
			"puuid", uuid.New().String(),
		),
	).With(args...))
}

func levelFromString(name string, fallback LogLevel) LogLevel {
	switch strings.ToUpper(name) {
		case "NONE":
			return LogLevel_None
		case "ERROR":
			return LogLevel_Error
		case "WARNING":
			return LogLevel_Warning
		case "INFO":
			return LogLevel_Info
		case "DEBUG":
			return LogLevel_Debug
		default:
			return fallback
	}
}

func setLogLevel() {
	level = levelFromString(os.Getenv("LOG_LEVEL"), level)
}

func SetLevel(l LogLevel) {
	level = l
}

func setMetric() {
	if os.Getenv("NO_METRIC") != "" {
		emitMetric = false
	}
}

func setTraceback() {
	if os.Getenv("GOTRACEBACK") == "" {
		debug.SetTraceback("crash")
	}
}

func Fatal(err error) {
	Error(
		"Fatal error", "fatal-error",
		"error", err,
		"stack", string(debug.Stack()),
	)
	panic(err)
}

func FatalIf(err error) {
	if err != nil {
		Fatal(err)
	}
}

func Assert(condition bool, message string) {
	if !condition {
		Fatal(errors.New("assertion failed: " + message))
	}
}

func Unreachable() {
	Assert(false, "Unreachable code was reached")
}

func setHostname() {
	var err error
	hostname, err = os.Hostname()
	FatalIf(err)
}

func Init(args ...any) {
	SetLoggerOutput(os.Stdout, args...)
	setLogLevel()
	setMetric()
	setTraceback()
	setHostname()
}