1 Event Bus
GnomeZworc edited this page 2025-04-24 14:16:31 +02:00
This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

A simple event queue

🧱 Design simple en Go

🎛️ Structure Event

type EventType string

const (
	EventStart   EventType = "start"
	EventStop    EventType = "stop"
	EventReboot  EventType = "reboot"
	EventAttach  EventType = "attach-disk"
	EventDetach  EventType = "detach-disk"
)

type VMEvent struct {
	Type   EventType
	VMID   string
	Params map[string]string // optionnel selon le type
}

📬 EventQueue (thread-safe FIFO + notify)

type EventQueue struct {
	queue  []VMEvent
	lock   sync.Mutex
	signal chan struct{}
}

func NewEventQueue() *EventQueue {
	return &EventQueue{
		queue:  make([]VMEvent, 0),
		signal: make(chan struct{}, 1),
	}
}

func (eq *EventQueue) Push(ev VMEvent) {
	eq.lock.Lock()
	defer eq.lock.Unlock()
	eq.queue = append(eq.queue, ev)

	select {
	case eq.signal <- struct{}{}:
	default:
		// si déjà notify, pas besoin de spammer
	}
}

func (eq *EventQueue) Pop() (VMEvent, bool) {
	eq.lock.Lock()
	defer eq.lock.Unlock()

	if len(eq.queue) == 0 {
		return VMEvent{}, false
	}

	ev := eq.queue[0]
	eq.queue = eq.queue[1:]
	return ev, true
}

🔁 Boucle d'exécution FIFO

func StartEventLoop(eq *EventQueue, manager *Manager) {
	go func() {
		for {
			<-eq.signal // bloquant jusqu'à ce quun event arrive

			for {
				ev, ok := eq.Pop()
				if !ok {
					break
				}

				log.Printf("⏳ Processing event %s for VM %s", ev.Type, ev.VMID)

				switch ev.Type {
				case EventStart:
					manager.StartVMByID(ev.VMID)
				case EventStop:
					manager.StopVMByID(ev.VMID)
				case EventAttach:
					manager.AttachDisk(ev.VMID, ev.Params["path"])
				case EventDetach:
					manager.DetachDisk(ev.VMID, ev.Params["path"])
				default:
					log.Printf("⚠️ Unknown event type: %s", ev.Type)
				}
			}
		}
	}()
}

🌐 Exposition via HTTP (exemple minimal)

func handleStartVM(w http.ResponseWriter, r *http.Request, eq *EventQueue) {
	vmID := r.URL.Query().Get("id")
	if vmID == "" {
		http.Error(w, "missing id", 400)
		return
	}
	eq.Push(VMEvent{Type: EventStart, VMID: vmID})
	fmt.Fprintf(w, "Start request enqueued")
}

🔔 Résumé de la comm' inter-composants

[API HTTP]   --(Push VMEvent)-->   [EventQueue] --(notify chan)--> [EventLoop]
                                                       |
                                       [Pop / Switch exec based on event type]