Untitled

mail@pastecode.io avatar
unknown
golang
2 years ago
11 kB
1
Indexable
Never
// Contains the implementation of a LSP server.

package lsp

import (
	"errors"
	"github.com/cmu440/lspnet"
	"fmt" // need to delete this
	"container/list"
	"encoding/json" // for json Marshal
)


type pair struct {
    pair_id, pair_payload interface{} 
}


type server struct {
	connection *lspnet.UDPConn // ?

	// [EpochLimit: 5, EpochMillis: 2000, WindowSize: 1, MaxBackOffInterval: 0,MaxUnackedMessages: 1]
	EpochLimit int
	EpochMillis int
	WindowSize int
	MaxBackOffInterval int
	MaxUnackedMessages int

    read_request chan string
    read_response_id chan int
    read_response_msg chan string // need to turn back to [] byte in Read()

	client_cur_index int // current client_id number (e.g. current there are 5 clients already, then the number here can be 6, which means the next client will have an id value 6)
	m map[int]client_2 // map conn_id to client struct!! // keep track of client's IP address+port with its client_id (so if resend connection message, we do not generate a new client_id??)
	
	queue *list.List // use list so the size will not be fixed
}


type client_2 struct {
	client_id int
	server_sequence_number int // server's copy of sequence number for a specific client
	client_sequence_number int // server's expecting client's sequence number?
	ack_status int // which message it has acked?

    // client's addr
    client_addr *lspnet.UDPAddr
    // map (unordered data)
    unordered_queue map[int]string // type?

	// store un-ordered data message (priority queue, may use a heap) (for seq num that are too large, so we can not yet put into the queue)
	// priority_queue heap.Heap ??
	// probably also the sequence of message to send back to the client???
}


// NewServer creates, initiates, and returns a new server. This function should
// NOT block. Instead, it should spawn one or more goroutines (to handle things
// like accepting incoming client connections, triggering epoch events at
// fixed intervals, synchronizing events using a for-select loop like you saw in
// project 0, etc.) and immediately return. It should return a non-nil error if
// there was an error resolving or listening on the specified port number.
func NewServer(port int, params *Params) (Server, error) {
	// create a new server and initialize
	var LSPserver server

	port_string := fmt.Sprintf("%d", port)
    fmt.Println("port_string = ", port_string)

	addr_string := "127.0.0.1: " + port_string

	a, error := lspnet.ResolveUDPAddr("udp", addr_string)
	if error != nil {
        fmt.Println(error)
        return &LSPserver, error
    }

	connection, error := lspnet.ListenUDP("udp", a)
	if error != nil {
        fmt.Println(error)
        return &LSPserver, error
    }

    LSPserver.connection = connection
    LSPserver.EpochLimit = params.EpochLimit
    LSPserver.EpochMillis = params.EpochMillis
    LSPserver.WindowSize = params.WindowSize
    LSPserver.MaxBackOffInterval = params.MaxBackOffInterval
    LSPserver.MaxUnackedMessages = params.MaxUnackedMessages

    LSPserver.m = make(map[int]client_2) // !!!

    LSPserver.queue = list.New() // ??????

    LSPserver.read_request = make(chan string)
    LSPserver.read_response_id = make(chan int)
    LSPserver.read_response_msg = make(chan string)

	// start read goroutine
	go LSPserver.read_routine() // ??????? always reading

	return &LSPserver, nil
}




/*

This is where we turn UDP into LSP

We continue to read message, do some processing, and store it in the queue.
For the 3 different cases, we need to do different processing and send it to the main routine

we need to know the latest sequence number that is put into the queue, and only the number that is continuously larger than the current sequence number can be added to the queue

we do not need to call read_routine again and again, because it runs when server starts and never ends
Just continue to send sth into the queue

We just need tone read_routine
*/
func (s *server) read_routine(){
    s.client_cur_index += 1

	for {
        select {
        default:
            // fmt.Println("in read_routine!!!!!!")
            message_temp := make([]byte, 1000)
            // message_read, _, _ := s.connection.Read(message_temp[:]) // ???
            n, addr_, _ := s.connection.ReadFromUDP(message_temp) // ???
            // fmt.Println("message_temp = ", string(message_temp))
            
            var message Message // ??????

            error := json.Unmarshal(message_temp[:n], &message) // need to read limited length
            if error != nil{
                fmt.Println("error in Unmarshal")
                return 
            }

            // fmt.Println("message_read = ", message_read)
            fmt.Printf("server: message after unmarshal = %s", &message) // ?

            if message.Type == 0{ // or 0? connect case (do not need to forward to main routine?)  lspnet.MsgConnect?

                var new_client client_2 
                new_client.client_id = s.client_cur_index
                new_client.server_sequence_number = message.SeqNum
                new_client.client_sequence_number = message.SeqNum

                new_client.client_addr = addr_ // added

                // also need to initialize a priority queue? (no for now, and we can just use a sliding window to achieve this)

                s.m[s.client_cur_index] = new_client
                s.client_cur_index += 1

                // m["uid"] = make(map[string]T)
                // s.m[s.client_cur_index].unordered_queue = make(map[int]string) // added, initialize

                if entry, ok := s.m[s.client_cur_index]; ok { // added
                   entry.unordered_queue = make(map[int]string)
                
                   s.m[s.client_cur_index] = entry
                }

                // send ack message to client (with client's connect_id)
                ack_message := NewAck(new_client.client_id, message.SeqNum)
                message_bytes, error := json.Marshal(ack_message)
                if error != nil{
                    return 
                }

                // fmt.Println("server new connection before write to udp")

                s.connection.WriteToUDP(message_bytes, addr_) // 需要看會不會block (如果會block就用write_routine)

                // fmt.Println("server new connection after write to udp")
                
            }

            if message.Type == 1{ // data (按照順序傳進list/queue)

                this_seq_num := message.SeqNum
                this_client_id := message.ConnID

                // check checksum and size first
                this_size := message.Size
                this_payload := message.Payload

                // fmt.Println("message.Size = ", message.Size)
                // fmt.Println("len of payload = ", len(message.Payload))

                if len(this_payload) != this_size{
                    fmt.Println("the size is incorrect")
                    return 
                }

                // checksum
                this_checksum := CalculateChecksum(message.ConnID, message.SeqNum, message.Size, message.Payload)
                
                if this_checksum != message.Checksum{
                    fmt.Println("the checksum is incorrect")
                    return 
                }

                if entry, ok := s.m[this_client_id]; ok {
                    entry.unordered_queue = make(map[int]string)
                    s.m[this_client_id] = entry // ???
                }

                // s.m[this_client_id].unordered_queue = make(map[int]string)

                if entry2, ok2 := s.m[this_client_id]; ok2 {
                    entry2.unordered_queue[this_seq_num] = string(this_payload)
                    s.m[this_client_id] = entry2 // ???
                }

                // s.m[this_client_id].unordered_queue[this_seq_num] = string(this_payload)


                // send ack message back to client
                ack_message := NewAck(this_client_id, this_seq_num)
                message_bytes, error := json.Marshal(ack_message)
                if error != nil{
                    fmt.Println("error")
                    return 
                }
                // s.Write(this_client_id, message_bytes)
                s.connection.WriteToUDP(message_bytes, s.m[this_client_id].client_addr) // modified

                s.read_response_id <- this_client_id
                s.read_response_msg <- string(this_payload)

            }

            if message.Type == 2{ // ack (do NOT need to do anything for checkpoint?)

                this_client_id := message.ConnID

                if entry, ok := s.m[this_client_id]; ok {
                    entry.server_sequence_number += 1
                    s.m[this_client_id] = entry
                }
                
            }

            if message.Type == 3{ // cAck
                this_client_id := message.ConnID
                
                if entry, ok := s.m[this_client_id]; ok {
                    entry.server_sequence_number += 1
                    s.m[this_client_id] = entry
                }
            }

        }
        
    }

}

// probably do not need write_routine, because we can just write it back in the main routine?


/*
LSP's read
will have a received message, but we need to know which client is from, so we need to return client_id

Just taking things out of server's queue 

從queue拿出來,回傳給他

main_routine -> 傳到read_routine,用channel溝通,不要直接在這邊改動s.queue (避免race condition)
*/
func (s *server) Read() (int, []byte, error) {

    conn_id := <- s.read_response_id
    
    msg_string := <- s.read_response_msg
    
    // fmt.Printf("server read: conn_id = %s", conn_id)
    // fmt.Printf("server read: msg sent = %s", msg_string)

    return conn_id, []byte(msg_string), nil
	
   
}

func (s *server) Write(connId int, payload []byte) error {
    
    size := len(payload)
    checksum := CalculateChecksum(connId, s.m[connId].server_sequence_number, size, payload)
    msgToSer := NewData(connId, s.m[connId].server_sequence_number, size, payload, checksum)
    msgJson, err := json.Marshal(msgToSer)

    if err != nil {
        fmt.Println(err.Error())
        return err
    }

    addr := s.m[connId].client_addr // added
    _, err = s.connection.WriteToUDP(msgJson, addr)
    if err != nil {
        fmt.Println(err.Error())
        return err
    }

    fmt.Printf("server write: %s", msgToSer)

	return nil
}

func (s *server) CloseConn(connId int) error {
	fmt.Println("CloseConn!!!")

	// delete the client from server's map

	return errors.New("not yet implemented")
}

func (s *server) Close() error {
	fmt.Println("Close!!!")

	// stop the server and clean all resources

	return errors.New("not yet implemented")
}