how to use client context to start child spans at server side - open-telemetry

from an angular client i have injected context and sending through headers
try {
const ctx = api.trace.setSpan(
api.context.active(),
parentSpan
);
const tracer = trace.getTracerProvider().getTracer('Ui-Service');
let span = tracer.startSpan('start_Client_spans', undefined, ctx);
const carrier:{traceparent:string} = {
traceparent:""
};
const propagator = new W3CTraceContextPropagator();
propagator.inject(
api.trace.setSpanContext(api.context.active(), span.spanContext()),
carrier,
api.defaultTextMapSetter,
)
const clone = req.clone({
headers: req.headers
.set('ot-tracer-traceid' ,carrier.traceparent)
});
span.end()
return clone;
} catch (e) {
console.log(e)
throw e
}
}
server side code below here the context is extracted from headers and trying to be injected to start further spans at server side so that client request is parent and server requests are child spans of the same trace id but currently both server and client are having separate trace ids
const carrier = req.headers["ot-tracer-traceid"]
const propagator = new W3CTraceContextPropagator();
if(carrier?.length>0){
const clientContext = propagator.extract(
api.context.active(),
carrier,
api.defaultTextMapGetter
);
const newTracer = api.trace.getTracer("test","1.0.0")
// create server span using the client context
//below code snippet does create spans but individual spans , but i am expecting them to use the client context
const serverSpan = newTracer.startSpan('operationName', undefined, clientContext);
console.log(newTracer);
}
can some one hint me where am i getting wrong ?

Related

How does request.context in Parse Cloud Code work?

Back in Parse Server 3.0 update, there was an addition of request.context to pass data between BeforeSave and AfterSave as documented here:
https://docs.parseplatform.org/cloudcode/guide/#using-request-context
However, I'm having a bit of trouble understanding how and when Parse runs this code in the example.
const beforeSave = function beforeSave(request) {
const { object: role } = request;
// Get users that will be added to the users relation.
const usersOp = role.op('users');
if (usersOp && usersOp.relationsToAdd.length > 0) {
// add the users being added to the request context
request.context = { buyers: usersOp.relationsToAdd };
}
};
const afterSave = function afterSave(request) {
const { object: role, context } = request;
if (context && context.buyers) {
const purchasedItem = getItemFromRole(role);
const promises = context.buyers.map(emailBuyer.bind(null, purchasedItem));
item.increment('orderCount', context.buyers.length);
promises.push(item.save(null, { useMasterKey: true }));
Promise.all(promises).catch(request.log.error.bind(request.log));
}
};
in other examples, cloud code functions are run via Parse.Cloud.beforeSave or Parse.Cloud.afterSave. In this example above, the function beforeSave is assigned to a
const beforeSave.
Why was this done and is this supposed to be placed inside main.js top level or inside another function?

Resetting/Restart Rxjs Stream on form submit

I have an input field which when submitted makes a http call and then plots a graph. When I click on any node of graph, same http call is made and results are appended to the previous results and graph is updated. It is working fine till here. I am using scan operator to update my resultset. Now, what I want is to reset the resultset (ie - return new original response) whenever I am submitting the input form and append to resultset when graph node is clicked. Any ideas on how this can be achieved? Mainly how can I reset this stream on form submit? Or how can I show new data on form submit and updated data on node click
Here linkingDetailsByAccount$ makes the http call and gets the data from the server.
this.linkingDetailsByAccountSubject.next(account);
Same code is called on node click as well as on form submit which then activates my stream.
graph$ = this.linkingDetailsByAccount$.pipe(
pluck('graph'),
scan((linkedDetails, adjacency) => {
const { nodes: linkedNodes = [], edges: linkedEdges = [] } = linkedDetails;
const { nodes: newNodes = [], edges: newEdges = [] } = adjacency;
const updatedNodes = differenceBy(newNodes, linkedNodes, 'id');
const updatedEdges = differenceWith(
newEdges,
linkedEdges,
(newEdge: VisEdge, existingEdge: VisEdge) => newEdge.from === existingEdge.to
);
const allNodes = [...linkedNodes, ...updatedNodes];
const allEdges = [...linkedEdges, ...updatedEdges];
return {
nodes: allNodes,
edges: allEdges
};
}, {} as NodesEdges)
);
Appreciate any inputs on this.
Thanks,
Vatsal
Edit: Updated answer when I received more details from OP.
How I would do it is turn it into a mini Redux like state manager.
So the scan operator should take in functions or event objects.
First you want to store the first initial state from the initial HTTP call you make. You will use this object to reset your state on form submission.
Then create a graphEvents subject.
interface UpdateGraphEvent {
type: 'Update';
account: any;
}
interface ResetGraphEvent {
type: 'Reset';
account: any;
}
type GraphEvent = UpdateGraphEvent | ResetGraphEvent;
this.graphEvents$ = new Subject<GraphEvent>();
Then you can use your new graphEvents$ subject to replace uses of linkingDetailsByAccountSubject.
// When you want to update with new data.
this.graphEvent$.next({type: 'Update', account: account});
// when you want to reset with initial data.
this.graphEvent$.next({type: 'Reset', account: this.initialAccount});
Then use it in your stream.
graph$ = this.graphEvent$.pipe(
pluck('graph'),
scan((linkedDetails, event: GraphEvent) => {
if (event.type === 'Reset') {
return {
nodes: event.account.nodes,
edges: event.account.edges,
}
}
const { nodes: linkedNodes = [], edges: linkedEdges = [] } = linkedDetails;
const { nodes: newNodes = [], edges: newEdges = [] } = event.account;
const updatedNodes = differenceBy(newNodes, linkedNodes, 'id');
const updatedEdges = differenceWith(
newEdges,
linkedEdges,
(newEdge: VisEdge, existingEdge: VisEdge) => newEdge.from === existingEdge.to
);
const allNodes = [...linkedNodes, ...updatedNodes];
const allEdges = [...linkedEdges, ...updatedEdges];
return {
nodes: allNodes,
edges: allEdges
};
}, {} as NodesEdges)
);
The graphEvent$ will be a Subject that emits those events (GraphEvent).

Custom google cast receiver stuck in "Load is in progress"

My custom v3 CAF receiver app is successfully playing the first few live & vod assets. After that, it gets into a state were media commands are being queued because "Load is in progress". It is still (successfully) fetching manifests, but MEDIA_STATUS remains "buffering". The log then shows:
[ 4.537s] [cast.receiver.MediaManager] Load is in progress, media command is being queued.
[ 5.893s] [cast.receiver.MediaManager] Buffering state changed, isPlayerBuffering: true old time: 0 current time: 0
[ 5.897s] [cast.receiver.MediaManager] Sending broadcast status message
CastContext Core event: {"type":"MEDIA_STATUS","mediaStatus":{"mediaSessionId":1,"playbackRate":1,"playerState":"BUFFERING","currentTime":0,"supportedMediaCommands":12303,"volume":{"level":1,"muted":false},"currentItemId":1,"repeatMode":"REPEAT_OFF","liveSeekableRange":{"start":0,"end":20.000999927520752,"isMovingWindow":true,"isLiveDone":false}}}
CastContext MEDIA_STATUS event: {"type":"MEDIA_STATUS","mediaStatus":{"mediaSessionId":1,"playbackRate":1,"playerState":"BUFFERING","currentTime":0,"supportedMediaCommands":12303,"volume":{"level":1,"muted":false},"currentItemId":1,"repeatMode":"REPEAT_OFF","liveSeekableRange":{"start":0,"end":20.000999927520752,"isMovingWindow":true,"isLiveDone":false}}}
Fetch finished loading: GET "(manifest url)".
No errors are shown.
Even after closing and restarting the cast session, the issue remains. The cast device itself has to be rebooted to resolve it. It looks like data is kept between sessions.
It could be important to note that the cast receiver app is not published yet. It is hosted on a local network.
My questions are:
What could be the cause of this stuck behavior?
Is there any session data kept between session?
How to fully reset the cast receiver app, without the necessity to restart the cast device.
The receiver app itself is very basic. Other than license wrapping it resembles the vanilla example app:
const { cast } = window;
const TAG = "CastContext";
class CastStore {
static instance = null;
error = observable.box();
framerate = observable.box();
static getInstance() {
if (!CastStore.instance) {
CastStore.instance = new CastStore();
}
return CastStore.instance;
}
get debugLog() {
return this.framerate.get();
}
get errorLog() {
return this.error.get();
}
init() {
const context = cast.framework.CastReceiverContext.getInstance();
const playerManager = context.getPlayerManager();
playerManager.addEventListener(
cast.framework.events.category.CORE,
event => {
console.log(TAG, "Core event: " + JSON.stringify(event));
}
);
playerManager.addEventListener(
cast.framework.events.EventType.MEDIA_STATUS,
event => {
console.log(TAG, "MEDIA_STATUS event: " + JSON.stringify(event));
}
);
playerManager.addEventListener(
cast.framework.events.EventType.BITRATE_CHANGED,
event => {
console.log(TAG, "BITRATE_CHANGED event: " + JSON.stringify(event));
runInAction(() => {
this.framerate.set(`bitrate: ${event.totalBitrate}`);
});
}
);
playerManager.addEventListener(
cast.framework.events.EventType.ERROR,
event => {
console.log(TAG, "ERROR event: " + JSON.stringify(event));
runInAction(() => {
this.error.set(`Error detailedErrorCode: ${event.detailedErrorCode}`);
});
}
);
// intercept the LOAD request to be able to read in a contentId and get data.
this.loadHandler = new LoadHandler();
playerManager.setMessageInterceptor(
cast.framework.messages.MessageType.LOAD,
loadRequestData => {
this.framerate.set(null);
this.error.set(null);
console.log(TAG, "LOAD message: " + JSON.stringify(loadRequestData));
if (!loadRequestData.media) {
const error = new cast.framework.messages.ErrorData(
cast.framework.messages.ErrorType.LOAD_CANCELLED
);
error.reason = cast.framework.messages.ErrorReason.INVALID_PARAM;
return error;
}
if (!loadRequestData.media.entity) {
// Copy the value from contentId for legacy reasons if needed
loadRequestData.media.entity = loadRequestData.media.contentId;
}
// notify loadMedia
this.loadHandler.onLoadMedia(loadRequestData, playerManager);
return loadRequestData;
}
);
const playbackConfig = new cast.framework.PlaybackConfig();
// intercept license requests & responses
playbackConfig.licenseRequestHandler = requestInfo => {
const challenge = requestInfo.content;
const { castToken } = this.loadHandler;
const wrappedRequest = DrmLicenseHelper.wrapLicenseRequest(
challenge,
castToken
);
requestInfo.content = wrappedRequest;
return requestInfo;
};
playbackConfig.licenseHandler = license => {
const unwrappedLicense = DrmLicenseHelper.unwrapLicenseResponse(license);
return unwrappedLicense;
};
// Duration of buffered media in seconds to start/resume playback after auto-paused due to buffering; default is 10.
playbackConfig.autoResumeDuration = 4;
// Minimum number of buffered segments to start/resume playback.
playbackConfig.initialBandwidth = 1200000;
context.start({
touchScreenOptimizedApp: true,
playbackConfig: playbackConfig,
supportedCommands: cast.framework.messages.Command.ALL_BASIC_MEDIA
});
}
}
The LoadHandler optionally adds a proxy (I'm using a cors-anywhere proxy to remove the origin header), and stores the castToken for licenseRequests:
class LoadHandler {
CORS_USE_PROXY = true;
CORS_PROXY = "http://192.168.0.127:8003";
castToken = null;
onLoadMedia(loadRequestData, playerManager) {
if (!loadRequestData) {
return;
}
const { media } = loadRequestData;
// disable cors for local testing
if (this.CORS_USE_PROXY) {
media.contentId = `${this.CORS_PROXY}/${media.contentId}`;
}
const { customData } = media;
if (customData) {
const { licenseUrl, castToken } = customData;
// install cast token
this.castToken = castToken;
// handle license URL
if (licenseUrl) {
const playbackConfig = playerManager.getPlaybackConfig();
playbackConfig.licenseUrl = licenseUrl;
const { contentType } = loadRequestData.media;
// Dash: "application/dash+xml"
playbackConfig.protectionSystem = cast.framework.ContentProtection.WIDEVINE;
// disable cors for local testing
if (this.CORS_USE_PROXY) {
playbackConfig.licenseUrl = `${this.CORS_PROXY}/${licenseUrl}`;
}
}
}
}
}
The DrmHelper wraps the license request to add the castToken and base64-encodes the whole. The license response is base64-decoded and unwrapped lateron:
export default class DrmLicenseHelper {
static wrapLicenseRequest(challenge, castToken) {
const wrapped = {};
wrapped.AuthToken = castToken;
wrapped.Payload = fromByteArray(new Uint8Array(challenge));
const wrappedJson = JSON.stringify(wrapped);
const wrappedLicenseRequest = fromByteArray(
new TextEncoder().encode(wrappedJson)
);
return wrappedLicenseRequest;
}
static unwrapLicenseResponse(license) {
try {
const responseString = String.fromCharCode.apply(String, license);
const responseJson = JSON.parse(responseString);
const rawLicenseBase64 = responseJson.license;
const decodedLicense = toByteArray(rawLicenseBase64);
return decodedLicense;
} catch (e) {
return license;
}
}
}
The handler for cast.framework.messages.MessageType.LOAD should always return:
the (possibly modified) loadRequestData, or
a promise for the (possibly modified) loadRequestData
null to discard the load request (I'm not 100% sure this works for load requests)
If you do not do this, the load request stays in the queue and any new request is queued after the initial one.
In your handler, you return an error if !loadRequestData.media, which will get you into that state. Another possibility is an exception in the load request handler, which will also get you in that state.
I guess we have a different approach and send everything possible through sendMessage, when we loading stuff we create a new cast.framework.messages.LoadRequestData() which we load with playerManager.load(loadRequest).
But I guess that you might be testing this on an integrated Chromecast, we see this problems as well!?
I suggest that you do one or more
Enable gzip compression on all responses!!!
Stop playback playerManager.stop() (maybe in the interseptor?)
Change how the licenseUrl is set
How we set licenseUrl
playerManager.setMediaPlaybackInfoHandler((loadRequestData, playbackConfig) => {
playbackConfig.licenseUrl = loadRequestData.customData.licenseUrl;
return playbackConfig;
}
);

Client (javascript) unable to receive image or binary from server using boost beast and opencv

I used one of one of the example of boost::beast web server asynchronous to communicate with client javascript using websocket. I am attempting to do the simple receiving image and write it in server side.
The result I receive in the server side is a broken jpg image.
Thank you in advance.
client-side (javascript)
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
var img = document.getElementById("image");
var ws = null;
connect.onclick = function() {
ws = new WebSocket(uri.value);
ws.onopen = function(ev) {
messages.innerText += "[connection opened]\n";
};
ws.onclose = function(ev) {
messages.innerText += "[connection closed]\n";
};
ws.onmessage = function(ev) {
messages.innerText += ev.data + "\n";
};
ws.onerror = function(ev) {
messages.innerText += "[error]\n";
console.log(ev);
};
};
disconnect.onclick = function() {
ws.close();
};
send.onclick = function() {
var canvas1 = ctx.getImageData(0,0,img.width,img.height);
var binary = new Uint8Array(img.data.length);
for (var i=0; i<img.data.length; ++i) {
binary[i] = img.data[i];
}
ws.send(binary.buffer);
}
server-side
void on_write(boost::system::error_code ec,
std::size_t bytes_transferred)
{
boost::ignore_unused(bytes_transferred);
if(ec)
return fail(ec, "write");
buffer_.consume(buffer_.size());
std::cout << "on write before do read\n";
ws_.async_read(
buffer_,
boost::asio::bind_executor(
strand_,
std::bind(
&session::on_read,
shared_from_this(),
std::placeholders::_1,
std::placeholders::_2)));
uint8_t *buf = new uint8_t [bytes_transferred];
boost::asio::buffer_copy(boost::asio::buffer(buf,bytes_transferred),buffer_.data(),bytes_transferred);
::cv::Mat mImg(400,320,CV_8UC3,buf);
::cv::imwrite("file.jpg",mImg);
delete [] buf;
}
I first recommend refactoring your code into small testable functions.
Write a function like this:
template <class AsyncStream, class CompletionToken>
auto
async_write_opencv_image(AsyncStream&, CompletionToken&& token)
{
// write composed op here
}
Using this, you can feed in a boost::beast::test::stream to the function which will allow you to manually inspect the buffers to ensure the image's correctness.
This has the advantage that now your image writing code is stream-agnostic so you can swap it out for any other type.
If you need any assistance in this regard, there's ample documentation on boost.org as well as live-help on the cpplang slack team.
Edit:
Here's a wandbox example how to potentially also setup a unit test for websockets as well:
https://wandbox.org/permlink/EixDmotCphJwiDZ1

redux observable map not invoked

I have this code, and failing to understand why I am not getting inside the map function (where I have the comment "I AM NEVER GETTING TO THIS PART OF THE CODE"):
export const fiveCPMonitoringLoadEpic = (action$, store) =>
action$
.ofType(
FIVE_CP_MONITORING_ACTION_TYPES.LOAD_FIVE_CP_MONITORING_DATA_STARTED
)
.debounceTime(250)
.switchMap(action => {
const params = action.params;
const siteId = { params };
// getting site's EDC accounts (observable):
const siteEdcAccount$ = getSiteEDCAccountsObservable(params);
const result$ = siteEdcAccount$.map(edcResponse => {
// getting here - all good so far.
const edcAccount = edcResponse[0];
// creating another observable (from promise - nothing special)
const fiveCPMonitoringEvent$ = getFiveCPAndTransmissionEventsObservable(
{
...params,
edcAccountId: edcAccount.utilityAccountNumber
}
);
fiveCPMonitoringEvent$.subscribe(x => {
// this is working... I am getting to this part of the code
// --------------------------------------------------------
console.log(x);
console.log('I am getting this printed out as expected');
});
return fiveCPMonitoringEvent$.map(events => {
// I NEVER GET TO THIS PART!!!!!
// -----------------------------
console.log('----- forecast-----');
// according to response - request the prediction (from the event start time if ACTIVE event exists, or from current time if no active event)
const activeEvent = DrEventUtils.getActiveEvent(events);
if (activeEvent) {
// get event start time
const startTime = activeEvent.startTime;
// return getPredictionMeasurementsObservable({...params, startTime}
const predictions = getPredictionMock(startTime - 300);
return Observable.of(predictions).delay(Math.random() * 2000);
} else {
// return getPredictionMeasurementsObservable({...params}
const predictions = getPredictionMock(
DateUtils.getLocalDateInUtcSeconds(new Date().getTime())
);
return Observable.of(predictions).delay(Math.random() * 2000);
}
});
can someone please shed some light here?
why when using subscribe it is working, but when using map on the observable it is not?
isn't map suppose to be invoked every time the observable fires?
Thanks,
Jim.
Until you subscribe to your observable, it is cold and does not emit values. Once you subscribe to it, the map will be invoked. This is a feature of rxjs meant to avoid operations that make no change (= no cunsumer uses the values). There are numerous blog posts on the subject, search 'cold vs hot obserables' on google

Resources