30 Mart 2021 Salı

Data Distribution Unit (DDU) Nedir

Giriş
Data Distribution Unit (DDU) Mission Computer (Görev Bilgisayarı) ile diğer cihazlar (peripherals) arasındaki haberleşmeyi sağlayan kısımdır. Şeklen şöyle




Böylece şu işlevler sağlanır
1. Yalıtım
Görev Bilgisayarı, çevre birimlerinden yalıtılır

2. Farklı Cihazlar
Görev Bilgisayarına farklı cinste ve tipte çevre birimleri takılabilir

3. Yedeklilik (Redundancy)
Çevre birimlerinin yedekli olması sağlanabilir. DDU bir "windowing" kuralı uygulayarak (örneğin sinyal gücü, cihazın kalitesi, kullanıcı tercihi vs) aynı bilgileri veren farklı cihazlar arasında birisini tercih eder ve Görev Bilgisayarına bu cihaza ait bilgiyi gönderir. Eğer cihaz bozulursa, DDU otomatik olarak yedek cihaza geçer. Böylece Görev Bilgisayarında bir bozulma olmaz.

Mimari
Aslında DDU ile yazılım mimarilerinden birisi olan Hexagonal Architecture veya diğer ismiyle "Ports and Adapters" birbirlerine bayağı benziyorlar. Aslında Hexagonal Architecture ise çok daha genel bir mimaridir. Herhangi bir yerde kullanılabilir.

Fakat DDU genellikle kapalı sistemlerde kullanılır. Bu kapalı sistem gemi, uçak, araba gibi yazılım ağırlıklı bir sistemdir.

Çevre Birimleri
DDU terminolojisinden içinde çevre birimlerle haberleşmeyi sağlayan kısma
 -Peripheral Interface Unit (PIU),
- System Interface Unit (SIU)
gibi bir isim verilir.

Data Distribution Unit Donanımı
DDU tercihen tek bir kutu şeklindedir. Çevre birimlerine çok farklı protokol ve kablolama ile bağlanırken, çekirdek tarafına çıkış veren arayüz standart ve çokça kullanılan bir şeydir.

Veri Yapısı
Veri yapısı 3 başlık altında toplanabilir. Eğer Domain Driven Design kullanıyorsak şöyle gruplarız

 Application Entities
1. PIU Entities
Bir PIU'dan gelen mesaj olduğu gibi, başka PIU'lara dağıtılır. 
2. Mission Computer Entities
Mission Computer'a gönderilecek kayıtlardır

Domain Entities
1. System Entities
Failover, SubsystemState, Simulation Message Generation gibi logic içeren bilgilerin tutulduğu kayıtlar
2. Summary Entities. Bazı sistemlerde buna Data Reduction deniliyor.
PIU'lardan bir sürü veri akar. Bazı önemli alanları birleştirerek ekranda göstermek veya log'lamak isteyebilirim.

Tasarım Kuralı
Bence bu tür yazılımlarda Command Pattern bayağı kullanışlı. 

1. Çevresel cihazdan gelen veri bir Command içinde işlenir. 
2. Command entity'lere sadece yazma işlemi yapar. Command hangi entity tipini güncelleyeceğini bilir.
Örneğin bir Command sadece PIU kayıdını güncellerken, bir başka Command PIU, Summary Entity, Mission Computer kayıtlarının hepsini güncelleyebilir.

3. Entity'lere Listener takılır. Güncellenen entity bilgisi ile ne yapılacağı Listener'ın bileceği şeydir.

Command yazma işleminde şu entity'lerden bir veya bir kaç tanesini günceller.

1. PIU Entity Güncelleme
PIU Entity değerini güncelleyebilir. Yeni veri Listener aracılığıyla diğer PIU'lara yayınlanır. Eğer gerekiyorsa Failover kayıtlarına bakılarak, cihaz seçili veya etkinse, Mission Computer kayıları da güncellenir.

2. System Entity Güncelleme
System Entity aynı işi yapan bir veya daha fazla alıcıdan kuvvetli olanın tercih edildiği değerleri içerir. Bazen cihazlar yedeklidir, bazen de farklı cihazların kesişen işlevleri vardır. Örneğin hız hem GPS hem de Hız Ölçer ile ölçülebilir. Bu cihazlar arasında bir önceliklendirme koymak isteyebilirim. Böylece eğer çalışıyorsa hızı önce GPS ile ölçerim, eğer çalışmıyorsa Hız Ölçeri  ile ölçmek isteyebilirim. 

Tercih etme işi aslında bence DDS'teki Ownership Qos kullanımına benziyor.

3. Mission Computer Entity Güncelleme
Bazı bilgiler de görev bilgisayarına gönderilir. Gönderilen bilgi muhtemelen birden fazla cihazın bilgisinin bileşimini içeren bir mesaj şeklinde olacaktır.

4. Summary Entity Güncelleme
PIU'dan gelen bir sürü mesajı özet şeklinde ekranda gösterme veya loglama amacıyla kullanılır. Bu entity'ye takılan Listener gerekli işlemi gerçekleştirir.

Sınıf ve Mesaj İsimlendirme
DDU boru şeklinde olmasına rağmen çok katmanlı olabilir. Bu durumda sınıf isimlendirmesi önem kazanıyor.


Mesaj İsimleri
Mesaj isimleri XFromSensor, YToSensor şeklinde olabilir.

Konfigürasyon
Aynı tipte alıcılardan birden fazla varsa, her XFromSensor mesajına sourceDevice diye bir alan eklenebilir

DDU Int Bileşeni - Receive
network -> XFromSensorTopic -> XFromSensorTopicCommand -> XFromSensorTopicDTO

Yani : XFromSensorTopic okuyorsa ve DTO gönderiyorsa, command olarak XFromSensorTopicCommand çalıştırır. Burada DTO'ya dönüşüm olmasına rağmen önemsiz olduğu için command isminde belirtilmiyor.

DDU Core Bileşeni
XFromSensorTopicDTO -> XFromSensorCommand -> XRecordListener -> XRecordToSensorDTO

Yani : XFromSensorTopicDTO okuyorsa, command olarak XFromSensorCommand çalıştırır. Burada command ismi artık Topic, gibi şeyleri içermez, çünkü core işlemi yapmaktadır.

DDU Int Bileşeni - Send
XRecordToSensorDTO -> XRecordToSensorTopicCommand -> network

Yani : XRecordToSensorDTO okuyorsa ve topic gönderiyorsa, command olarak XRecordToSensorTopicCommand çalıştırır. Burada DTO'dan tekrar Topic'e dönüşüm olduğu için command isminde belirtiliyor.

29 Mart 2021 Pazartesi

OLTP vs OLAP

Giriş
Veri tabanları iki farklı iş için tasarlanır. Açıklaması şöyle
As you probably know, databases are divided into two types: Online Transactional Processing (OLTP) and Online Analytical Processing (OLAP).
Bu ikisinin farklılıklar şöyle
OLTP and OLAP describe two very different data processing methods, and, therefore, they have different database requirements.

Characteristics OLTP OLAP
Data queried in one request Small (a few rows) Large
Real-time update         Yes         No
Transactions         Yes         No
Concurrency         High         Low
Query pattern         Similar Varies a lot
Özetlersek açıklaması şöyle
OLTP systems are born to handle transaction data: they enable the real-time execution of large transactions with many concurrent queries and require fast response times. On the other hand, OLAP requires running complex queries on large numbers of records. OLAP systems have high throughput but do not offer low query latencies or high queries per second (QPS) like the OLTP systems.
1. OLTP
Açıklaması şöyle
Years ago, databases made little distinction between OLTP and OLAP. Instead, one database processed both types of requests. However, as the data volume grew, it became difficult to process two types of workloads in a single database. Most significantly, the different workload types interfered with each other.

Thus, to meet the special needs of OLAP workloads, people designed a separate database that only processed OLAP workloads. They exported data from OLTP databases to OLAP databases, and processed the OLAP workloads there. Separating the OLTP and OLAP workloads resolved the conflicts between the two workloads, but it also introduced external data replication. During the replication, it was hard to ensure that data was consistent and in real time.
2. OLAP - Eski/Arşiv Veri
OLAP eski ve arşiv veriyle uğraşır. Transaction miktarı azdır ve daha çok sorgu yapar. Sorgular karmaşıktır ve aggregation miktarı çoktur.

OLAP ismindeki online eskiden kalan bir kelime. Açıklaması şöyle
It is simply a remnant of olden times, when it was used in contrast to batch processing. "Online" here means "interactive", that is, requests to the database are processed as they come and responses are given more or less immediately, or at least as soon as they are available. Batch processing would collect requests into, well, batches, and execute them on schedule; responses would be given after the entire batch execution (e.g. next morning).
Örnek
Bir örnek şöyle
PostGre is usually used in OLTP scenarios with a bit of OLAP.
That is fine as long as you understand the difference between them.
For example, if a public-facing endpoint contains a very complex query that loads a lot of data and does complex operations, it’s probably a good indicator that it should be treated as OLAP and that endpoint refactored to adopt a different strategy.
Örnek
Açıklaması şöyle
Redshift supports some SQL functions and queries which would generally only be necessary with large data warehouse applications. For example, PERCENTILE_CONT computes a linear interpolation to return a percentile.
Şöyle yaparız
SELECT
    TOP 10 salesid,
    sum(pricepaid),
    percentile_cont(0.6) WITHIN GROUP (
        ORDER BY 
            salesid
    ),
    median (salesid)
FROM
    sales
GROUP BY
    salesid,
    pricepaid;
Örnek
OLAP veri tabanlarında one-to-many olması beklenen ilişkiler bile çok fazla normalize edilmiş olabilir.
Normalization Nedir yazısına bakabilirsiniz.

Aşağıdaki örnekte User, Department isimli iki farlı tablo var. Daha sonra bu iki farklı tabloyu birleştiren UserDepartmentTable tablosu var.

UsersTable
UserID  FirstName   LastName
234     John        Doe
516     Jane        Doe
123     Foo         Bar
DepartmentsTable
DepartmentID   Name
1              Sales
2              HR
3              IT
UserDepartmentTable
UserDepartmentID   UserID   Department
1                  234      2
2                  516      2
3                  123      1
RequestTable
RequestID   UserID   <...>
1           516      blah
2           516      blah
3           234      blah


26 Mart 2021 Cuma

Reactive Programlama Nedir?

Reactive Programlama Nedir?
Korkmayın nükleer teknoloji ile alakası yok :) Ancak plaza İngilizcesiyle artık her yerde karşımıza çıkan bir “hot topic”.

Not : LMAX tarafından geliştirilen Distruptor Reactive Programlamaya bir başka seçenek. Bir örnek burada

Okudum Ama Anlamadım
Evet yazılım dünyasının derdi bu zaten. Okuyup anlayamamak :) Anlamlı kelimeleri yan yana dizince anlaşılmaz cümleler nasıl ortaya çıkıyor bilmiyorum.

Observable, Observers, Schedulers, Flux, Mono, Backpressure vs. kavramları. Hiyeroglif gibi çizilmiş, bakanı kör eden “Marble Diagram” şekilleri. Geçelim.

Yani ?
Reactive Programlamada önemli iki şey var.
1. Komuta cevap vermek
2. İşlemciyi sürekli meşgul tutmak

Yani  asynchronous, non-blocking, event-driven, vıdı vıdı kelimelerinin özü bu iki madde. Bu iki maddenin önem sırası sizin geliştirme yaptığınız dünyaya göre değişebiliyor. 

Yani mobile ve backend dünyalarında farklı şeyler ifade ediyorlar.

Diyelim ki elimize telefonu aldık, bir uygulama çalıştırdık. Sonra telefonu yan döndürdüm. Ne olmasını beklerim ? Telefon “döndür/rotate” diye bir event yayınlasın. Benim sevgili uygulamam da bunu dinlesin ve hemen (yani non-blocking şekilde) kendisini döndürsün.

Uygulamayı kapatmaya karar verdim. O zaman hemen kapansın. Beni bekletmesin, acelem var :) Hani bazen Windows’ta bir işleme başlarsın ve iptal edemezsin ya. Bu olmasın  işte :)

Bu telefon dünyasının (dükkan ismiyle alakası yoktur) bakış açısı. 

Veya cloud üzerinde çalışan bir uygulamam olsun ve bana sürekli veri aksın. Bu veriyi  işlemek için 100 thread açayım. Yani “I/O bound” işlemler bolca var. Bu thread’ler için mutlaka context switch olacaktır, hatta daha kötüsü birisi ötekini bekletecektir, ve ben bu boşa geçen sürenin parasını bulut sağlayıcısına ödeyeceğim. Zengin miyim ? Değilim :) O zaman 4 thread açsam ve bunları sürekli meşgul tutsam nasıl olur? Bunun için her şeyi  asynchronous,  non-blocking yapmam lazım. Veri tabanına bağlantı mı açacağım? Ben işlemi başlatayım, sonra başka bir işe geçeyim. Sonucu işletim sistemi bana söylesin. 

Bu aslında aynı yemek pişirmeye benziyor. Ne kadar çok işi paralel yaparsam o kadar   hızlı biter. 

Reactive programlama çok daha fazlası aslında ancak birisi bana kısaca özetle derse bunları söylerdim. 

22 Mart 2021 Pazartesi

HTTP Durum Kodları - 1XX Informational Kodları

100 Continue
Sanırım büyük dosyaları upload ederken kullanılır.

101 Switching Protocols
Açıklaması şöyle
The correct status code to use here is without a doubt 301 Moved Permanently.

101 Switching Protocols is an internal status code that a server generally uses to automatically negotiate certain types of connections. It's not used when changing the URL from http to https. If you're curious about how it works, you can read about the 101 status code and the protocol upgrade mechanism on MDN, but you'll never need to know about it as a webmaster.

As a general rule, you should never directly use 100 or 200 series status codes unless you are actually developing web server software. The 300 and 400 series codes (especially 301, 302, and 404) are the ones you'll want to pay attention to when running a simple website.
102 Processing
Açıklaması şöyle. Sanırım uzun süren işlemlerde kullanılır.
The 102 (Processing) status code is an interim response used to inform the client that the server has accepted the complete request, but has not yet completed it. This status code SHOULD only be sent when the server has a reasonable expectation that the request will take significant time to complete. As  guidance, if a method is taking longer than 20 seconds (a reasonable, but arbitrary value) to process the server SHOULD return a 102 (Processing) response. The server MUST send a final response after the request has been completed.
Methods can potentially take a long period of time to process, especially methods that support the Depth header. In such cases the client may time-out the connection while waiting for a response. To prevent this the server may return a 102 (Processing) status code to indicate to the client that the server is still processing the method.
103 Early Hints
Açıklaması şöyle
Normally, when the browser sends a request, the server will receive it and process the request in less than a second and send an HTTP 200 OK response ...

Using the HTTP 103 Early Hints, however, there is room to improve the page rendering speed.

Once the server is updated with the HTTP 103 feature, when a browser sends a request, if the server knows that the content needs resources like style.css, script.js, and so on, then it will hint (respond) with the HTTP 103 Early Hints response to the browser to preload the content ...

Then, once the server processed the complete response, it will send normal HTTP 200 OK to the browser.

This process will help in the page rendering speed as the browser preloads the content ahead.

HTTP Durum Kodları - 2XX SUCCESS Kodları

Giriş
Açıklaması şöyle.
The 2xx (Successful) class of status code indicates that the client's request was successfully received, understood, and accepted.
200 - OK
Açıklaması şöyle.
200 means the server experienced no problems and has a representation of the results for the client to consume.
Sunucudaki bir dosyaya GET isteği gönderdiğimizi varsayalım. Cevap olarak 200 ile başlayan bir satır almamız tüm dosyayı indirdiğimiz anlamına gelmez. Http isteği bir bütün olarak düşünülmeli. Açıklaması şöyle.
HTTP 200 is generated by the server, and only means that it understood the request and thinks it is able to fulfill it (e.g. the file is actually there). All sorts of errors may occur during the transmission of the full response document (network connection breaking, packet loss, etc) which will not show up in the HTTP response, but need to be detected separately.
201 Created
Açıklaması şöyle. PUT isteği ile bir resource ilk defa yaratılırsa bu cevap döner.
If the target resource does not have a current representation and the PUT successfully creates one, then the origin server MUST inform the user agent by sending a 201 (Created) response. If the target resource does have a current representation and that representation is successfully modified in accordance with the state of the enclosed representation, then the origin server MUST send either a 200 (OK) or a 204 (No Content) response to indicate successful completion of the request.
202 Accepted - Async taskİsteğin alındığını belirtir. 200'den farkı gönderilen isteğin daha sonra asenkron olarak işleneceğini ifade etmesidir.

Örnek
Açıklaması şöyle
Assume that your web/mobile application UI accepts a task request from a user, such as uploading an image or creating a profile. The backend will take considerable time to process the task, which can’t be completed within the scope of an HTTP request.

The typical pattern is that the backend accepts the request, validates it, and returns HTTP 202 status to the UI, denoting that the task has been accepted for processing. 

203 - Non-Authoritative Information (since HTTP/1.1)
Açıklaması şöyle.
203 means that the response was modified between the authoritative server and the client. 
204 - No Content
Client tarafından gönderilen isteğe "No Result" gibi bir cevap vermek istersek kullanılabilir. Rest servisini normalde vereceği cevap şöyle olsun.
{
  "results": [
    {
      "name": "Pancakes",
      ....
    },
    {
      "name": "French Fries",
      ....
    }
  ]
}
Ancak dönülen cevap boş ise 204 ve şöyle bir cevap gönderilebilir.
{
  "results": []
}
205 - Reset Content
Örnek ver

206 - Partial Content
Açıklaması şöyle.
206 appears to be designed for returning a large resource over multiple responses. It also requires that the client ask for a part of the content in the headers (so pagination via query strings does not qualify).
207 Multi-Status
Açıklaması şöyle. Birden fazla işin sonucu dönüleceği zaman kullanılabilir.
A Multi-Status response conveys information about multiple resources in situations where multiple status codes might be appropriate. The default Multi-Status response body is a text/xml or application/xml HTTP entity with a 'multistatus' root element. Further elements contain 200, 300, 400, and 500 series status codes generated during the method invocation. 100 series status codes SHOULD NOT be recorded in a 'response' XML element.
Although '207' is used as the overall response status code, the recipient needs to consult the contents of the multistatus response body for further information about the success or failure of the method execution. The response MAY be used in success, partial success and also in failure situations.

HTTP Durum Kodları - 3XX REDIRECTION Kodları

Giriş
Redirection yerine HSTS kullanılabilir. Açıklaması şöyle.
If a user try to access some random http://example.com, HSTS will transform the request into https://example.com, however the website need to have a valid certificate in order to function properly.
300 Multiple Choices
Örnek ver

301 Moved Permanently
Örnek ver

302 Found (Previously "Moved temporarily")
302 ile tarayıcıyı başka sayfaya yönlendirebilmek mümkün. 302 kodu ile beraber yönlendirilen URL bilgisini de göndermek gerekir. 302 cevabı şöyledir.
$ curl -I https://google.net/
HTTP/1.1 302 Found
Location: https://www.google.com/
Cache-Control: private
Content-Type: text/html; charset=UTF-8
...
Örnek
302 durum kodu URL Shortening servisleri tarafından kullanılır.

Örnek
Wicket ile 302 göndermek için exception atılıyor. Örneğin RestartResponseException veya RedirectToUrlException ile bu gerçekleştirilebiliyor.

Eğer orijinal sayfaya tekrar dönülmesi gerekiyorsa RestartResponseAtInterceptPageException  kullanılıyor.

303 See Other
Örnek ver

304 Not Modified
Örnek ver

305 Use Proxy
Örnek ver

307 Temporary Redirect
Örnek ver

11 Mart 2021 Perşembe

NGINX - nginx.conf Dosyası - Limit Request

Giriş
Açıklaması şöyle
If the requests rate exceeds the rate configured for a zone, their processing is delayed such that requests are processed at a defined rate. Excessive requests are delayed until their number exceeds the maximum burst size in which case the request is terminated with an error. By default, the maximum burst size is equal to zero
Örnek
Şöyle yaparız
limit_req_zone $server_name zone=one:10m rate=100r/s;

server {
    location /search/ {
        limit_req zone=one burst=200;
    }
  ...
}