Skip to content

Commit

Permalink
Tuned up error handling, and new version detection.
Browse files Browse the repository at this point in the history
compressing all of wiretap monitor content now also for speed.

Signed-off-by: Dave Shanley <dave@quobix.com>
  • Loading branch information
daveshanley committed Jul 23, 2023
1 parent ed32acd commit 0b361ae
Show file tree
Hide file tree
Showing 16 changed files with 271 additions and 39 deletions.
3 changes: 3 additions & 0 deletions cmd/root_command.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,9 @@ var (

var config shared.WiretapConfiguration

// set version.
config.Version = Version

if configFlag == "" {
// see if a configuration file exists in the current directory or in the user's home directory.
local, _ := os.Stat("wiretap.yaml")
Expand Down
5 changes: 3 additions & 2 deletions cmd/serve_monitor.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,8 @@ func serveMonitor(wiretapConfig *shared.WiretapConfiguration) {
indexString := string(bytes)

// replace the port in the index.html file and serve it.
indexString = strings.ReplaceAll(indexString, shared.WiretapPortPlaceholder, wiretapConfig.WebSocketPort)
indexString = strings.ReplaceAll(strings.ReplaceAll(indexString, shared.WiretapPortPlaceholder, wiretapConfig.WebSocketPort),
shared.WiretapVersionPlaceholder, wiretapConfig.Version)

// handle index will serve a modified index.html from the embedded filesystem.
// this is so the monitor can connect to the websocket on the correct port.
Expand All @@ -65,7 +66,7 @@ func serveMonitor(wiretapConfig *shared.WiretapConfiguration) {
mux.HandleFunc("/", handleIndex)

// compress everything!
handlers.CompressHandler(fileServer)
fileServer = handlers.CompressHandler(fileServer)

// handle the assets
mux.Handle("/assets/", http.StripPrefix("/assets", fileServer))
Expand Down
21 changes: 20 additions & 1 deletion daemon/wiretap_broadcast.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,12 @@
package daemon

import (
"encoding/json"
"fmt"
"github.com/google/uuid"
"github.com/pb33f/libopenapi-validator/errors"
"github.com/pb33f/ranch/model"
"github.com/pb33f/wiretap/shared"
"net/http"
)

Expand Down Expand Up @@ -52,13 +55,29 @@ func (ws *WiretapService) broadcastResponse(request *model.Request, response *ht

func (ws *WiretapService) broadcastResponseError(request *model.Request, response *http.Response, err error) {
id, _ := uuid.NewUUID()
title := "Response Error"
code := 500
if response != nil {
title = fmt.Sprintf("Response Error %d", response.StatusCode)
code = response.StatusCode
}

respBodyString, _ := json.Marshal(&shared.WiretapError{
Title: title,
Status: code,
Detail: err.Error(),
})

resp := buildResponse(request, response)
resp.Response.Body = string(respBodyString)

ws.broadcastChan.Send(&model.Message{
Id: &id,
DestinationId: request.Id,
Error: err,
Channel: WiretapBroadcastChan,
Destination: WiretapBroadcastChan,
Payload: buildResponse(request, response),
Payload: resp,
Direction: model.ResponseDir,
})
}
Expand Down
2 changes: 2 additions & 0 deletions shared/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ type WiretapConfiguration struct {
Variables map[string]string `json:"variables,omitempty" yaml:"variables,omitempty"`
Spec string `json:"contract,omitempty" yaml:"contract,omitempty"`
CompiledVariables map[string]*CompiledVariable `json:"-" yaml:"-"`
Version string `json:"-" yaml:"-"`
StaticPathsCompiled []glob.Glob `json:"-" yaml:"-"`
CompiledPaths map[string]*CompiledPath `json:"-"`
FS embed.FS `json:"-"`
Expand Down Expand Up @@ -120,6 +121,7 @@ func (wpc *WiretapPathConfig) Compile(key string) *CompiledPath {

const ConfigKey = "config"
const WiretapPortPlaceholder = "%WIRETAP_PORT%"
const WiretapVersionPlaceholder = "%WIRETAP_VERSION%"
const IndexFile = "index.html"
const UILocation = "ui/dist"
const UIAssetsLocation = "ui/dist/assets"
10 changes: 5 additions & 5 deletions shared/error.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,11 @@ import "encoding/json"

// WiretapError is an rfc7807 compliant error struct
type WiretapError struct {
Type string `json:"type,omitempty"` // URI reference to the type of problem
Title string `json:"title"` // A short description of the issue
Status int `json:"status,omitempty"` // HTTP status code.
Detail string `json:"detail"` // explanation of the issue in detail.
Instance string `json:"instance"` // URI to the specific problem.
Type string `json:"type,omitempty"` // URI reference to the type of problem
Title string `json:"title"` // A short description of the issue
Status int `json:"status,omitempty"` // HTTP status code.
Detail string `json:"detail"` // explanation of the issue in detail.
Instance string `json:"instance,omitempty"` // URI to the specific problem.
}

func GenerateError(title string,
Expand Down
7 changes: 7 additions & 0 deletions ui/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,13 @@
<script>
sessionStorage.setItem('wiretapPort', '%WIRETAP_PORT%')
//sessionStorage.setItem('wiretapPort', '9092')
const version = '%WIRETAP_VERSION%';
const existingVersion = localStorage.getItem('wiretapVersion');
if (existingVersion !== version) {
localStorage.setItem('wiretapVersion', version);
localStorage.setItem('wiretapWipeCache', 'true');
}

</script>
<script type="module" src="/src/index.ts" defer></script>
<script type="module" src="/src/workers/link_cache_worker.ts"></script>
Expand Down
28 changes: 15 additions & 13 deletions ui/src/components/controls/controls.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,13 +70,13 @@ export class WiretapControlsComponent extends LitElement {
this.loadControlStateFromStorage().then((controls: WiretapControls) => {
if (!controls) {
this._controls = {
globalDelay: -1,
globalDelay: 0,
}
} else {
this._controls = controls;
}
// get the delay from the backend.
this.changeGlobalDelay(-1) // -1 won't update anything, but will return the current delay
this.changeGlobalDelay(0) // -1 won't update anything, but will return the current delay
});


Expand Down Expand Up @@ -125,18 +125,20 @@ export class WiretapControlsComponent extends LitElement {
}

changeGlobalDelay(delay: number) {
this._bus.publish({
destination: "/pub/queue/controls",
body: JSON.stringify(
{
id: RanchUtils.genUUID(),
requestCommand: ChangeDelayCommand,
payload: {
delay: delay
if (this._bus.getClient()?.connected) {
this._bus.publish({
destination: "/pub/queue/controls",
body: JSON.stringify(
{
id: RanchUtils.genUUID(),
requestCommand: ChangeDelayCommand,
payload: {
delay: delay
}
}
}
),
});
),
});
}
}

openSettings() {
Expand Down
13 changes: 12 additions & 1 deletion ui/src/components/kv-view/kv-view.css.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,18 @@ export default css`
font-size: 1em;
}
pre {
word-wrap: break-word;
white-space: pre-wrap;
max-width: 760px;
overflow-x: auto;
}
pre > code {
word-wrap: break-word;
white-space: pre-wrap;
}
Expand Down
2 changes: 1 addition & 1 deletion ui/src/components/kv-view/kv-view.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ export class KVViewComponent extends LitElement {
<tr>
<td><code>${i[0]}</code></td>
<td>
<pre><code>${unsafeHTML(Prism.highlight(JSON.stringify(i[1]), Prism.languages['json'], 'json'))}</pre></code>
<pre style=""><code style="white-space: pre-wrap; word-wrap: break-word;">${unsafeHTML(Prism.highlight(JSON.stringify(i[1], null, 2), Prism.languages['json'], 'json'))}</pre></code>
</td>
</tr>`
}
Expand Down
11 changes: 9 additions & 2 deletions ui/src/components/transaction/response-body.css.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,17 @@ export default css`
}
pre {
max-width: calc(100vw - 135px);
overflow-x: auto;
max-width: 960px;
word-wrap: break-word;
white-space: pre-wrap;
}
pre code {
white-space: pre-wrap;
word-wrap: break-word;
}
`
7 changes: 2 additions & 5 deletions ui/src/components/transaction/response-body.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,6 @@ export class ResponseBodyViewComponent extends LitElement {
</span>`;

switch (exct) {
case ContentTypeJSON:
return html`${ct}
<pre><code>${unsafeHTML(Prism.highlight(JSON.stringify(JSON.parse(this._httpResponse.responseBody), null, 2),
Prism.languages.json, 'json'))}</code></pre>`;
case ContentTypeXML:
return html`
<pre><code>${unsafeHTML(Prism.highlight(JSON.stringify(JSON.parse(this._httpResponse.responseBody), null, 2),
Expand All @@ -57,7 +53,8 @@ export class ResponseBodyViewComponent extends LitElement {

default:
return html`${ct}
<pre>${this._httpResponse.responseBody}</pre>`
<pre><code>${unsafeHTML(Prism.highlight(JSON.stringify(JSON.parse(this._httpResponse.responseBody), null, 2),
Prism.languages.json, 'json'))}</code></pre>`;
}
}

Expand Down
4 changes: 4 additions & 0 deletions ui/src/components/transaction/transaction-view.css.ts
Original file line number Diff line number Diff line change
Expand Up @@ -163,4 +163,8 @@ export default css`
color: var(--error-color);
}
.response-code {
font-size: 0.8rem;
}
`
11 changes: 9 additions & 2 deletions ui/src/components/transaction/transaction-view.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,11 @@ import transactionViewComponentCss from "./transaction-view.css";
import {KVViewComponent} from "@/components/kv-view/kv-view";
import sharedCss from "@/components/shared.css";
import {SlTab, SlTabGroup} from "@shoelace-style/shoelace";
import {ExtractHTTPCodeDefinition, ExtractStatusStyleFromCode} from "@/model/extract_status";
import {
ExtractHTTPCodeDefinition,
ExtractHTTPCodeDescription,
ExtractStatusStyleFromCode
} from "@/model/extract_status";
import {LinkMatch, TransactionLinkCache} from "@/model/link_cache";
import {HttpTransactionItemComponent} from "@/components/transaction/transaction-item";
import {HttpTransactionSelectedEvent, ViolationLocation} from "@/model/events";
Expand Down Expand Up @@ -267,7 +271,10 @@ export class HttpTransactionViewComponent extends LitElement {
<sl-tab slot="nav" panel="response-cookies" class="tab-secondary">Cookies</sl-tab>
<sl-tab-panel name="response-code">
<h2 class="${ExtractStatusStyleFromCode(resp)}">${resp.statusCode}</h2>
<p class="response-code">${ExtractHTTPCodeDefinition(resp)}</p>
<h3>${ExtractHTTPCodeDefinition(resp)}</h3>
<p class="response-code">
${ExtractHTTPCodeDescription(resp)}
</p>
</sl-tab-panel>
<sl-tab-panel name="response-headers">
${this._responseHeadersView}
Expand Down
Loading

0 comments on commit 0b361ae

Please sign in to comment.