Creating a New Theme (Test Post 1)

Introduction This tutorial will show you how to create a simple theme in Hugo. I assume that you are familiar with HTML, the bash command line, and that you are comfortable using Markdown to format content. I’ll explain how Hugo uses templates and how you can organize your templates to create a theme. I won’t cover using CSS to style your theme. We’ll start with creating a new site with a very basic template.

Shortcodes (Test Post 2)

Admonition

I'm title!

biu biu biu.

note

biu biu biu.

Without title.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
{{% admonition note "I'm title!" false %}}
biu biu biu.

{{% admonition type="note" title="note" details="true" %}}
biu biu biu.
{{% /admonition %}}

{{% admonition example %}}
Without title.
{{% /admonition %}}

{{% /admonition %}}

Syntax Highlighting (Test Post 3)

  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
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
package job

import (
	"context"
	"errors"
	"fmt"
	"log/slog"
	"sort"
	"sync"
	"sync/atomic"
	"time"

	"braces.dev/errtrace"
	"github.com/phucngodev/golang-web-framework/internal/config"
)

const (
	// job can retrieve and process.
	StatusNew = 0
	// job is leased and being processed.
	StatusLeased = 1
	// job not perform successfully.
	StatusFailed = 2
	// job perform successfully but delete fail.
	StatusDeleteFail = 3
	// default queue
	defaultQueue = "default"
	// default job delay.
	defaultDelay = 0
	// default max retries.
	defaultMaxRetries = 5
	// default job timeout is 2 minutes.
	defaultTimeout = 2
	// default job priority
	defaultPriority = 0
	// default job bursting size for one worker.
	defaultBurstSize = 10
	// default scaling interval 20 second.
	defaultScaleInterval   = 20
	defaultScaleUpFactor   = 0.8
	defaultScaleDownFactor = 0.2
)

var (
	ErrDeleteJobfail = errors.New("delete job fail")
)

type JobArgs interface {
	// Queue the queue name that job will be insert to.
	Queue() string
	// Job type
	Kind() string
	// Priority job priority.
	Priority() int
	// Job payload
	Payload() []byte
	// Job delay, default is no delay.
	Delay() time.Duration
	//MaxRetries max number of retries before set job to failed.
	MaxRetries() int
	// Job Timeout, default is 1 minutes.
	// if job requires more than 1 minutes to process, overrides Timeout function in worker job args.
	Timeout() time.Duration
}

type DefaultArgs struct{}

func (j DefaultArgs) Queue() string {
	return defaultQueue
}

func (j DefaultArgs) Priority() int {
	return defaultPriority
}

func (j DefaultArgs) Delay() time.Duration {
	return defaultDelay
}

func (j DefaultArgs) MaxRetries() int {
	return defaultMaxRetries
}

func (j DefaultArgs) Timeout() time.Duration {
	return defaultTimeout * time.Minute
}

type Worker interface {
	// Worker Work timeout.
	// Default timeout is 1 mins.
	Timeout() time.Duration
	// Work function to handle job.
	Work(ctx context.Context, job []byte) error
}

type DefaultWorker[T JobArgs] struct{}

func (w DefaultWorker[T]) Timeout() time.Duration {
	var t T
	return t.Timeout()
}

type QueueConfig struct {
	queue           string
	workerNum       int           // Maximum number of workers
	minWorkerNum    int           // Minimum number of workers (for autoscaling)
	scaleUpFactor   float64       // Factor to determine when to scale up
	scaleDownFactor float64       // Factor to determine when to scale down
	scaleInterval   time.Duration // Interval between scaling decisions
	currWorkNum     int
	activeJobs      int   // Number of jobs currently being processed by this queue
	scaleDownCount  int   // Number of workers to scale down
	nextWorkerId    int64 // Next ID to assign to a worker (atomic)
	lock            sync.Mutex
}

func (w *QueueConfig) addCurrWorkerNum() {
	defer w.lock.Unlock()
	w.lock.Lock()
	if w.currWorkNum >= w.workerNum {
		return
	}
	w.currWorkNum++
}

func (w *QueueConfig) removeCurrWorkerNum() {
	defer w.lock.Unlock()
	w.lock.Lock()
	if w.currWorkNum == 0 {
		return
	}
	w.currWorkNum--
}

func (w *QueueConfig) addActiveJob() {
	defer w.lock.Unlock()
	w.lock.Lock()
	w.activeJobs++
}

func (w *QueueConfig) removeActiveJob() {
	defer w.lock.Unlock()
	w.lock.Lock()
	if w.activeJobs > 0 {
		w.activeJobs--
	}
}

func (w *QueueConfig) getActiveJobs() int {
	defer w.lock.Unlock()
	w.lock.Lock()
	return w.activeJobs
}

func (q *QueueConfig) getWorkerUtilization() float64 {
	defer q.lock.Unlock()
	q.lock.Lock()

	if q.currWorkNum <= 0 {
		return 0
	}

	return float64(q.activeJobs) / float64(q.currWorkNum)
}

// InitializeQueue initializes the queue's internal state
func (q *QueueConfig) InitializeQueue() {
	defer q.lock.Unlock()
	q.lock.Lock()

	// Set initial values
	q.currWorkNum = 0
	q.activeJobs = 0
	q.scaleDownCount = 0
	atomic.StoreInt64(&q.nextWorkerId, int64(q.minWorkerNum+1))
}

// StartWorker starts a new worker if possible within the queue's limits
func (q *QueueConfig) StartWorker() bool {
	defer q.lock.Unlock()
	q.lock.Lock()

	if q.currWorkNum >= q.workerNum {
		return false // Maximum workers reached
	}

	q.currWorkNum++
	return true
}

// StopWorker stops a worker and updates the worker count appropriately
func (q *QueueConfig) StopWorker() {
	defer q.lock.Unlock()
	q.lock.Lock()

	if q.currWorkNum > 0 {
		q.currWorkNum--
	}
}

// HasCapacity checks if the queue can accept more workers
func (q *QueueConfig) HasCapacity() bool {
	defer q.lock.Unlock()
	q.lock.Lock()

	return q.currWorkNum < q.workerNum
}

// IsAtMinCapacity checks if the queue is at minimum worker capacity
func (q *QueueConfig) IsAtMinCapacity() bool {
	defer q.lock.Unlock()
	q.lock.Lock()

	return q.isAtMinCapacity()
}

// isAtMinCapacity is an unlocked helper to check for minimum capacity
func (q *QueueConfig) isAtMinCapacity() bool {
	return q.currWorkNum <= q.minWorkerNum
}

// ShouldScaleUp determines if the queue should add more workers based on utilization
func (q *QueueConfig) ShouldScaleUp() bool {
	utilization := q.getWorkerUtilization()
	return utilization >= q.scaleUpFactor && q.HasCapacity()
}

// ShouldScaleDown determines if the queue should remove workers based on utilization
func (q *QueueConfig) ShouldScaleDown() bool {
	utilization := q.getWorkerUtilization()
	return utilization <= q.scaleDownFactor && !q.IsAtMinCapacity()
}

// GetRunningWorkers returns the number of currently running workers accounting for scale-downs
func (q *QueueConfig) GetRunningWorkers() int {
	defer q.lock.Unlock()
	q.lock.Lock()

	// Account for workers marked for scale-down that may still be active
	return q.currWorkNum - q.scaleDownCount
}

// GetQueueStats returns comprehensive statistics about the queue
func (q *QueueConfig) GetQueueStats() QueueStats {
	defer q.lock.Unlock()
	q.lock.Lock()

	return QueueStats{
		QueueName:   q.queue,
		ActiveJobs:  q.activeJobs,
		Workers:     q.currWorkNum,
		Running:     q.currWorkNum,
		Capacity:    q.workerNum,
		MinWorkers:  q.minWorkerNum,
		Utilization: q.getWorkerUtilization(),
	}
}

type QueueStats struct {
	QueueName   string
	ActiveJobs  int
	Workers     int
	Running     int
	Capacity    int
	MinWorkers  int
	Utilization float64
}

type Queue struct {
	logger       *slog.Logger
	jobRepo      JobRepository
	workerNum    int
	lock         sync.Mutex
	pollInterval time.Duration
	workers      map[string]Worker
	queues       []*QueueConfig

	// server stop signal
	stop           chan (struct{})
	shutdownCtx    context.Context
	shutdownCancel context.CancelFunc
	// all workers have finished
	done chan (struct{})
	// Track all workers (both static and dynamic) to ensure proper shutdown
	workersWg sync.WaitGroup
}

func NewQueue(cfg *config.Config, logger *slog.Logger, repo JobRepository) *Queue {
	var queues []*QueueConfig
	for _, q := range cfg.Queue.Queues {
		// Set default values if not provided
		minWorkerNum := q.MinWorkerNum
		if minWorkerNum == 0 {
			minWorkerNum = 1
		}

		scaleUpFactor := q.ScaleUpFactor
		if scaleUpFactor == 0 {
			scaleUpFactor = defaultScaleUpFactor
		}

		scaleDownFactor := q.ScaleDownFactor
		if scaleDownFactor == 0 {
			scaleDownFactor = defaultScaleDownFactor
		}

		scaleInterval := cfg.Queue.ScaleInterval
		if scaleInterval == 0 {
			scaleInterval = defaultScaleInterval * time.Second // Default scaling check interval
		}

		newQueue := &QueueConfig{
			queue:           q.Queue,
			workerNum:       q.WorkerNum,
			minWorkerNum:    minWorkerNum,
			scaleUpFactor:   scaleUpFactor,
			scaleDownFactor: scaleDownFactor,
			scaleInterval:   scaleInterval,
		}
		newQueue.InitializeQueue() // Initialize the queue's internal state
		queues = append(queues, newQueue)
	}

	q := &Queue{
		logger:       logger,
		jobRepo:      repo,
		lock:         sync.Mutex{},
		pollInterval: cfg.Queue.PollInterval,
		workers:      make(map[string]Worker),
		queues:       queues,
		stop:         make(chan struct{}),
		done:         make(chan struct{}),
		workersWg:    sync.WaitGroup{},
	}
	q.shutdownCtx, q.shutdownCancel = context.WithCancel(context.Background())
	return q
}

func (w *Queue) Start(ctx context.Context) error {
	if len(w.workers) == 0 {
		w.logger.Error("no worker has been registered")
		return errtrace.New("no worker has been registered")
	}

	var workerNum int
	for _, q := range w.queues {
		workerNum += q.minWorkerNum // Start with minimum workers
	}

	if workerNum <= 0 {
		return errtrace.New("number of worker is 0")
	}

	var names []string
	for k := range w.workers {
		names = append(names, k)
	}

	sort.Strings(names)
	w.logger.Info("registered workers", "workers", names)

	// Start initial workers for each queue (minimum number)
	// These workers get IDs from 1 to minWorkerNum
	for _, q := range w.queues {
		q.InitializeQueue() // Initialize the queue's internal state
		for i := 0; i < q.minWorkerNum; i++ {
			w.workersWg.Add(1)
			go w.worker(ctx, q, i+1, &w.workersWg, true) // Initial workers should increment count
		}
	}

	// Start autoscaling goroutines for each queue
	for _, q := range w.queues {
		go w.startAutoscaling(ctx, q)
	}

	// Keep the main goroutine alive until stop signal
	<-w.stop

	// Wait for all workers (both initial and dynamic) to finish
	w.workersWg.Wait()
	close(w.done)
	return nil
}

// startAutoscaling runs the autoscaling loop for a specific queue
func (w *Queue) startAutoscaling(ctx context.Context, q *QueueConfig) {
	ticker := time.NewTicker(q.scaleInterval)
	defer ticker.Stop()

	for {
		select {
		case <-w.stop:
			return
		case <-ctx.Done():
			return
		case <-ticker.C:
			if q.ShouldScaleUp() {
				if q.StartWorker() {
					w.logger.Info("Scaling up worker", "queue", q.queue, "current_workers", q.GetRunningWorkers())
					// Start a new worker
					w.workersWg.Add(1)
					go func() {
						workerId := q.getNextWorkerId()
						w.worker(ctx, q, workerId, &w.workersWg, false)
					}()
				}
			} else if q.ShouldScaleDown() {
				q.markForScaleDown()
				w.logger.Info("Marked for scale down", "queue", q.queue, "current_workers", q.GetRunningWorkers())
			}
		}
	}
}

// Helper function to safely get the next worker ID (with atomic operations)
func (q *QueueConfig) getNextWorkerId() int {
	return int(atomic.AddInt64(&q.nextWorkerId, 1))
}

// addWorkerIfPossible tries to add a worker if we haven't reached the maximum
func (q *QueueConfig) addWorkerIfPossible() bool {
	return q.StartWorker()
}

// markForScaleDown signals that we should scale down when possible
func (q *QueueConfig) markForScaleDown() {
	defer q.lock.Unlock()
	q.lock.Lock()

	if !q.isAtMinCapacity() {
		q.scaleDownCount++
	}
}

// shouldScaleDown checks if the current worker should scale down
func (q *QueueConfig) shouldScaleDown() bool {
	defer q.lock.Unlock()
	q.lock.Lock()

	if q.scaleDownCount > 0 {
		q.scaleDownCount--
		return true
	}
	return false
}

func (w *Queue) worker(ctx context.Context, q *QueueConfig, workerId int, wg *sync.WaitGroup, shouldIncrementCount bool) {
	defer wg.Done()

	// Increment the worker count when the worker starts if needed
	if shouldIncrementCount {
		q.addCurrWorkerNum()
	}

	defer func() {
		// Decrement the worker count when the worker exits
		q.removeCurrWorkerNum()
		w.logger.Info("stopped worker on", "queue", q.queue, "worker_id", workerId)
	}()

	defer func() {
		if p := recover(); p != nil {
			w.logger.Error("worker panic", "queue", q.queue, "worker_id", workerId, "error", p)
		}
	}()

	w.logger.Info("starting worker on", "queue", q.queue, "worker_id", workerId)

	ticker := time.NewTicker(w.pollInterval)
	defer ticker.Stop()

	for {
		// Wait for the main poll ticker, or a shutdown signal.
		select {
		case <-w.stop:
			return
		case <-ctx.Done():
			return
		case <-ticker.C:
		}

		// Once woken up, try to drain the queue in a burst.
		// Process up to defaultBurstSize jobs in a burst
		for range defaultBurstSize {
			// Check for shutdown before every job.
			select {
			case <-w.stop:
				return
			case <-ctx.Done():
				return
			default:
			}

			job, err := w.jobRepo.Receive(ctx, q.queue)
			if err != nil {
				if !errors.Is(err, context.Canceled) && !errors.Is(err, context.DeadlineExceeded) {
					w.logger.Error("error receiving job during burst", "error", err)
				}
				// On DB error, stop this burst and wait for next ticker.
				break
			}
			if job == nil {
				// Queue is empty, stop this burst and wait for next ticker.
				break
			}

			// Process the job we found.
			w.doWorkOrRequeueJob(q, workerId, job)
			// And loop immediately to try and get another one.
		}

		// After the burst attempt (or if the queue was empty), we are idle.
		// Check if this idle worker should scale down.
		if q.shouldScaleDown() {
			w.logger.Info("Worker scaling down", "queue", q.queue, "worker_id", workerId)
			return
		}
	}
}

func (w *Queue) doWorkOrRequeueJob(q *QueueConfig, workerId int, job *Job) {
	q.addActiveJob() // Track active job for this queue
	defer func() {
		q.removeActiveJob() // Remove active job for this queue
	}()

	if err := w.doWork(q, workerId, job); err != nil {
		w.logger.Error("error when processing job", "queue", q.queue, "error", err)
		w.requeueJob(job, err)
	}
}

// doWork call registered worker.Work function to process job.
func (w *Queue) doWork(q *QueueConfig, workerId int, job *Job) error {
	w.logger.Info("processing message", "queue", q.queue, "worker_id", workerId, "kind", job.Kind, "priority", job.Priority, "job_id", job.ID)
	worker, ok := w.workers[job.Kind]
	if !ok {
		return errtrace.Errorf("handler not found for message type: %s", job.Kind)
	}

	before := time.Now()
	if err := w.executeJobWithTimeout(job.Payload, worker); err != nil {
		return errtrace.Errorf("error running job: %w", err)
	}

	w.logger.Info("ran job successfully", "queue", q.queue, "worker_id", workerId, "kind", job.Kind, "priority", job.Priority, "job_id", job.ID, "duration", time.Since(before))
	deleteCtx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
	defer cancel()
	if err := w.jobRepo.Delete(deleteCtx, job.ID); err != nil {
		return errtrace.Errorf("Error deleting job from jobs, it will be retried: %w %w", ErrDeleteJobfail, err)
	}

	return nil
}

// requeueJob enqueue job in case of error.
func (w *Queue) requeueJob(job *Job, err error) {
	updateCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
	defer cancel()

	w.logger.Info("--------reenqueue--------", "error", err)
	job.Error = err.Error()
	job.Status = StatusNew
	if job.Retries >= job.MaxRetries {
		job.Status = StatusFailed
	}

	if errors.Is(err, ErrDeleteJobfail) {
		job.Status = StatusDeleteFail
	}

	err = w.jobRepo.Update(updateCtx, job)
	if err != nil {
		w.logger.Error("error requeue job", "error", err)
	}
}

// registerWorker registers worker handler for specific job kind.
func registerWorker[T JobArgs](workers map[string]Worker, worker Worker) {
	var t T
	kind := t.Kind()
	if _, ok := workers[kind]; ok {
		panic(fmt.Sprintf("worker already exists for name: %s", kind))
	}

	workers[kind] = worker
}

// Stop stop queue. stop receive new job from queue and wait
// for all workers finishing their job before close.
func (w *Queue) Stop() {
	close(w.stop)

	// Set a timeout for graceful shutdown
	shutdownCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()

	// Create a goroutine that signals completion or timeout
	done := make(chan struct{})
	go func() {
		<-w.done
		close(done)
	}()

	select {
	case <-done:
		// Shutdown completed successfully
	case <-shutdownCtx.Done():
		// Timeout occurred, log a warning
		w.logger.Warn("Queue shutdown timed out after 30 seconds")
	}
}

func (w *Queue) executeJobWithTimeout(job []byte, worker Worker) error {
	ctx, cancel := context.WithTimeout(w.shutdownCtx, worker.Timeout())
	defer cancel()

	errChan := make(chan error, 1)
	go func() {
		defer func() {
			if r := recover(); r != nil {
				errChan <- fmt.Errorf("panic in worker.Work: %v", r)
			}
		}()
		errChan <- worker.Work(ctx, job)
	}()

	select {
	case err := <-errChan:
		return err
	case <-ctx.Done():
		return errtrace.Wrap(ctx.Err())
	}
}
1
2
3
function helloWorld () {
  alert("Hello, World!")
}