I am trying to make this example work. It is supposed to create two nodes with mdns support. Mdns is supposed to announce the peer every second, each peer is setup to print a statement once a peer is found.
When running it, the console output is merely empty. It prints out some garbage error in my concern: (node:51841) ExperimentalWarning: Readable[Symbol.asyncIterator] is an experimental feature. This feature could change at any time
How do i enable debugging log so that i can try to understand what is going on under the hood ?
I would like to verify the mdns announce packets are issued, and possibly received, or not.
Alternatively, i am trying to use the bootstrap module to begin over wan peers, though expect it to be much slower, thus i would prefer to use mdns.
I tried to add various configuration and modules without much success, it is not clear to me if i am required to use the gossip module if i only want to announce some data on the dht. stuff like that.
any help is appreciated.
const Libp2p = require('libp2p')
const MulticastDNS = require('libp2p-mdns')
const KadDHT = require('libp2p-kad-dht')
const Bootstrap = require('libp2p-bootstrap')
const TCP = require('libp2p-tcp')
const Mplex = require('libp2p-mplex')
const { NOISE } = require('libp2p-noise')
const GossipSub = require('libp2p-gossipsub')
const { FaultTolerance } = require('libp2p/src/transport-manager')
const CID = require('cids')
const all = require('it-all')
const delay = require('delay')
const bootstrapers = [
'/ip4/104.131.131.82/tcp/4001/p2p/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ',
'/ip4/104.236.176.52/tcp/4001/p2p/QmSoLnSGccFuZQJzRadHn95W2CrSFmZuTdDWP8HXaHca9z',
'/ip4/104.236.179.241/tcp/4001/p2p/QmSoLPppuBtQSGwKDZT2M73ULpjvfd3aZ6ha4oFGL1KrGM',
'/ip4/162.243.248.213/tcp/4001/p2p/QmSoLueR4xBeUbY9WZ9xGUUxunbKWcrNFTDAadQJmocnWm',
'/ip4/128.199.219.111/tcp/4001/p2p/QmSoLSafTMBsPKadTEgaXctDQVcqN88CNLHXMkTNwMKPnu',
'/ip4/104.236.76.40/tcp/4001/p2p/QmSoLV4Bbm51jM9C4gDYZQ9Cy3U6aXMJDAbzgu2fzaDs64',
'/ip4/178.62.158.247/tcp/4001/p2p/QmSoLer265NRgSp2LA3dPaeykiS1J6DifTC88f5uVQKNAd',
'/ip4/178.62.61.185/tcp/4001/p2p/QmSoLMeWqB7YGVLJN3pNLQpmmEk35v6wYtsMGLzSr5QBU3',
'/ip4/104.236.151.122/tcp/4001/p2p/QmSoLju6m7xTh3DuokvT3886QRYqxAzb1kShaanJgW36yx'
]
const createNode = () => {
return Libp2p.create({
addresses: {
listen: ['/ip4/0.0.0.0/tcp/0']
},
modules: {
transport: [ TCP ],
streamMuxer: [ Mplex ],
connEncryption: [ NOISE ],
// peerDiscovery: [ MulticastDNS ],
// peerDiscovery: [ MulticastDNS ],
peerDiscovery: [ Bootstrap, MulticastDNS ],
dht: KadDHT,
pubsub: GossipSub
},
transportManager: {
faultTolerance: FaultTolerance.NO_FATAL
},
config: {
peerDiscovery: {
autoDial: true,
[MulticastDNS.tag]: {
broadcast: true,
interval: 1000,
enabled: true
},
[Bootstrap.tag]: {
interval: 1000,
enabled: true,
list: bootstrapers
},
[GossipSub.tag]: {
enabled: true,
emitSelf: true,
signMessages: true,
strictSigning: true
},
mdns: {
broadcast: true,
interval: 1000,
enabled: true
},
bootstrap: {
interval: 1000,
enabled: true,
list: bootstrapers
},
pubsub: {
enabled: true,
emitSelf: true,
signMessages: true,
strictSigning: true
},
},
dht: {
enabled: true
}
}
})
}
( async () => {
const [node1, node2] = await Promise.all([
createNode(),
createNode()
])
node1.on('peer:discovery', (peer) => console.log('Discovered:', peer.id.toB58String()))
node2.on('peer:discovery', (peer) => console.log('Discovered:', peer.id.toB58String()))
await Promise.all([
node1.start(),
node2.start()
])
// const cid = new CID('QmTp9VkYvnHyrqKQuFPiuZkiX9gPcqj6x5LJ1rmWuSySnL')
// await node1.contentRouting.provide(cid)
// await delay(3000)
// console.log("looking for providers...")
// const providers = await all(node2.contentRouting.findProviders(cid, { timeout: 5000 }))
// console.log('Found provider:', providers[0].id.toB58String())
})()
edit: found out i could use DEBUG environment variable to print debug statements, thouhg i still have problems with event system.
Logging
To enable debugging, configure the DEBUG environment variable. Start with DEBUG=*, it prints log lines like:
mss:select select: read "/noise" +1ms
libp2p:upgrader encrypting outbound connection to {"id":"QmRiNVP5NSGJPHLo256vNMTYW9VzsTKYm4dRG3GoJj37ah"} +12ms
libp2p:noise Stage 0 - Initiator starting to send first message. +14ms
Select stuff you want to print out using DEBUG=*noise ...
events
The probleme in OP code is that the peer:discovery event has an argument of type PeerID, not Peer. Thus the statements console.log('Discovered:', peer.id.toB58String()) is incorrect and should be replaced with console.log('Discovered:', peer.toB58String())
But one may have noticed the OP did not provide any error messages related to that. That happens because those event handlers are handled with an error silencer.
I am unsure what is going on, though, runnning below code will not trigger the exception with the "yo" message.
node1.on('peer:discovery', (peerID) => {
console.log(node1.peerId.toB58String(), "discovered:", peerID.toB58String())
throw "yo"
})
Related source code
const Libp2p = require('libp2p')
const MulticastDNS = require('libp2p-mdns')
const KadDHT = require('libp2p-kad-dht')
const Bootstrap = require('libp2p-bootstrap')
const TCP = require('libp2p-tcp')
const Mplex = require('libp2p-mplex')
const { NOISE } = require('libp2p-noise')
const CID = require('cids')
const all = require('it-all')
const delay = require('delay')
const bootstrapers = [
'/ip4/104.131.131.82/tcp/4001/p2p/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ',
'/ip4/104.236.176.52/tcp/4001/p2p/QmSoLnSGccFuZQJzRadHn95W2CrSFmZuTdDWP8HXaHca9z',
'/ip4/104.236.179.241/tcp/4001/p2p/QmSoLPppuBtQSGwKDZT2M73ULpjvfd3aZ6ha4oFGL1KrGM',
'/ip4/162.243.248.213/tcp/4001/p2p/QmSoLueR4xBeUbY9WZ9xGUUxunbKWcrNFTDAadQJmocnWm',
'/ip4/128.199.219.111/tcp/4001/p2p/QmSoLSafTMBsPKadTEgaXctDQVcqN88CNLHXMkTNwMKPnu',
'/ip4/104.236.76.40/tcp/4001/p2p/QmSoLV4Bbm51jM9C4gDYZQ9Cy3U6aXMJDAbzgu2fzaDs64',
'/ip4/178.62.158.247/tcp/4001/p2p/QmSoLer265NRgSp2LA3dPaeykiS1J6DifTC88f5uVQKNAd',
'/ip4/178.62.61.185/tcp/4001/p2p/QmSoLMeWqB7YGVLJN3pNLQpmmEk35v6wYtsMGLzSr5QBU3',
'/ip4/104.236.151.122/tcp/4001/p2p/QmSoLju6m7xTh3DuokvT3886QRYqxAzb1kShaanJgW36yx'
]
const createNode = () => {
return Libp2p.create({
addresses: {
listen: ['/ip4/0.0.0.0/tcp/0']
},
modules: {
transport: [ TCP ],
streamMuxer: [ Mplex ],
connEncryption: [ NOISE ],
// peerDiscovery: [ MulticastDNS ],
peerDiscovery: [ MulticastDNS ],
// peerDiscovery: [ Bootstrap, MulticastDNS ],
dht: KadDHT,
// pubsub: GossipSub
},
// transportManager: {
// faultTolerance: FaultTolerance.NO_FATAL
// },
config: {
peerDiscovery: {
autoDial: true,
[MulticastDNS.tag]: {
broadcast: true,
interval: 1000,
enabled: true
},
[Bootstrap.tag]: {
interval: 1000,
enabled: true,
list: bootstrapers
},
},
dht: {
enabled: true
}
}
})
}
( async () => {
const [node1, node2] = await Promise.all([
createNode(),
createNode()
])
node1.on('peer:discovery', (peerID) => {
console.log(node1.peerId.toB58String(), "discovered:", peerID.toB58String())
})
node2.on('peer:discovery', (peerID) => {
console.log(node2.peerId.toB58String(), "discovered:", peerID.toB58String())
})
node1.on('error', console.error)
node2.on('error', console.error)
await Promise.all([
node1.start(),
node2.start()
])
})()
Related
I'm using strapi 4 with nextjs.
In the app strapi holds music events for each user and each user should be able add and retrieve there own music events.
I am having trouble retrieving
each users music events from strapi 4
I have a custom route and custom controller
The custom route is in a file called custom-event.js and works ok it is as follows:
module.exports = {
routes: [
{
method: 'GET',
path: '/events/me',
handler: 'custom-controller.me',
config: {
me: {
auth: true,
policies: [],
middlewares: [],
}
}
},
],
}
The controller id a file called custom-controller.js and is as follows:
module.exports = createCoreController(modelUid, ({strapi }) => ({
async me(ctx) {
try {
const user = ctx.state.user;
if (!user) {
return ctx.badRequest(null, [
{messages: [{ id: 'No authorization header was found'}]}
])
}
// The line below works ok
console.log('user', user);
// The problem seems to be the line below
const data = await strapi.services.events.find({ user: user.id})
// This line does not show at all
console.log('data', data);
if (!data) {
return ctx.notFound()
}
return sanitizeEntity(data, { model: strapi.models.events })
} catch(err) {
ctx.body = err
}
}
}))
Note there are two console.logs the first console.log works it outputs the user info
The second console.log outputs the data it does not show at all. The result I get back
using insomnia is a 200 status and an empty object {}
The following line in the custom-controller.js seems to be where the problem lies it works for strapi 3 but does not seem to work for strapi 4
const data = await strapi.services.events.find({ user: user.id})
After struggling for long time, days infact, I eventually got it working. Below is the code I came up with. I found I needed two queries to the database, because I could not get the events to populate the images with one query. So I got the event ids and then used the event ids in a events query to get the events and images.
Heres the code below:
const utils = require('#strapi/utils')
const { sanitize } = utils
const { createCoreController } = require("#strapi/strapi").factories;
const modelUid = "api::event.event"
module.exports = createCoreController(modelUid, ({strapi }) => ({
async me(ctx) {
try {
const user = ctx.state.user;
if (!user) {
return ctx.badRequest(null, [
{messages: [{ id: 'No authorization header was found'}]}
])
}
// Get event ids
const events = await strapi
.db
.query('plugin::users-permissions.user')
.findMany({
where: {
id: user.id
},
populate: {
events: { select: 'id'}
}
})
if (!events) {
return ctx.notFound()
}
// Get the events into a format for the query
const newEvents = events[0].events.map(evt => ({ id: { $eq: evt.id}}))
// use the newly formatted newEvents in a query to get the users
// events and images
const eventsAndMedia = await strapi.db.query(modelUid).findMany({
where: {
$or: newEvents
},
populate: {image: true}
})
return sanitize.contentAPI.output(eventsAndMedia,
strapi.getModel(modelUid))
} catch(err) {
return ctx.internalServerError(err.message)
}
}
}))
In a react-native project using Realm-js, I've just created a clone of the app, integrated all libs, and copied over all src directories.
The app builds installs and runs on Android.
When i go through the authentication flow (which utilizes realm to store auth data), i ultimately get an error:
[ Error: RealmObject cannot be called as a function ]
login function:
async function login(username, password) {
try {
const result = await Api.login({
username: username,
pass: password,
});
const userAuthResult = await Db.updateAuth(result);
setUserAuth(userAuthResult);
} catch (err) {
console.log('[ ERROR ]:', err)
if (!err.message || err.message.includes('Network Error')) {
throw new Error('Connection error');
}
throw new Error('Wrong username or password');
}
}
and ive narrowed down the issue to Db.updateAuth(...)
updateAuth:
export const updateAuth = (params) => {
console.log(' [ HERE 1 ]')
const auth = {
id: params.id,
token: params.token,
refreshToken: params.refresh_token,
tokenExpiresAt: Math.floor(Date.now() / 1000) + 600, //params.expires_at,
federatedToken: params.federatedToken ?? '',
federatedTokenExpiresAt: params.federatedTokenExpiresAt ?? 0,
username: params.username,
name: params.name,
roleName: params.role_name,
roleId: params.role_id,
lastLogin: Math.floor(Date.now() / 1000),
};
console.log(' [ HERE 2 ]')
realm.write(() => {
console.log(' [ HERE 3 ]')
realm.create('Authorizations', auth, 'modified'); // PROBLEM
});
return auth;
};
inspecting the schema, i found theres no federatedToken propereties, yet in the auth update object, there are two. not sure why it wouldnt be throwing an error in the original non-cloned app.
authorizations schema:
AuthorizationsSchema.schema = {
name: 'Authorizations',
primaryKey: 'id',
properties: {
id: 'int',
token: 'string',
refreshToken: 'string',
tokenExpiresAt: 'int',
username: 'string',
name: 'string',
roleName: 'string',
roleId: 'int',
lastLogin: 'int',
},
};
Realm.js (class declaration) -> https://pastebin.pl/view/c903b2e2
from realm instantiation:
let realm = new Realm({
schema: [
schema.AccountSchema,
schema.AuthorizationsSchema,
schema.AvailableServiceSchema,
schema.FederatedTokensSchema,
schema.NoteSchema,
schema.PhotoSchema,
schema.PhotoUploadSchema,
schema.PrintQueueSchema,
schema.ProductSchema,
schema.ReportSchema,
schema.ServicesSchema,
schema.UploadQueueJobSchema,
schema.InvoicesSchema,
schema.TestSchema
],
schemaVersion: 60,
deleteRealmIfMigrationNeeded: true,
//path: './myrealm/data',
});
this logs the 1, 2, and 3 statements. The issue seems to come from the 'problem' line. Im not sure what exactly this error means, as there doesnt seem to be anything in realm's repo about it, and in the app this was cloned from, there was no issue with this line. I can also see other lines are throwing similar errors later on the user flows
Anyone know what this is about? or where i can learn more?
React-native: v64.2
realm-js: 10.6.0 (app cloned from was v10.2.0)
MacOS: 11.3 (M1 architecture)
in order to create you have the first call, the realm.write a method like this.
const storeInDataBase = (res,selectedfile) => {
try{
realm.write(() => {
var ID =
realm.objects(DocumentConverstionHistory).sorted('HistoryID', true).length > 0
? realm.objects(DocumentConverstionHistory).sorted('HistoryID', true)[0]
.HistoryID + 1
: 1;
realm.create(DocumentConverstionHistory, {
HistoryID: ID,
Name:`${selectedfile.displayname}.pdf`,
Uri:`file://${res.path()}`,
Date: `${new Date()}`
});
})
}catch(err){
alert(err.message)
}
}
Here is the schema file
export const DATABASENAME = 'documentconverter.realm';
export const DocumentConverstionHistory = "DocumentConverstionHistory"
export const DocumentConverstionHistorySchema = {
name: "DocumentConverstionHistory",
primaryKey: 'HistoryID',
properties: {
HistoryID: {type: 'int'},
Name: {type: 'string'},
Uri: {type: 'string?'},
Type: {type: 'string?'},
Size: {type: 'string?'},
Date: {type: 'date?'}
}
};
When I make changes to the database that affect UserProfiles, the client side is updated. For instance, if I change a weekday from true to false the UserProfile will appear or disappear on my computer screen. However, when I make a change to Attendances, for instance, create a new attendance record which should make a UserProfile appear nothing happens unless I reload the page. I assume it's to do with studnentUserIds not being rerun.
How do I make Meteor notice these changes?
This is being built using Meteor, React and mongoDB.
Meteor.publish('teacher.AdminDashboardContainer.userProfiles', function getStudentUserProfiles(rollCallDate) {
if (this.userId) {
const start = new Date(moment(rollCallDate).startOf('day').toISOString());
const end = new Date(moment(rollCallDate).endOf('day').toISOString());
const weekday = `student.days.${moment(rollCallDate).format('dddd').toLowerCase()}`;
const studentUserIds = Attendances.find({
$and: [
{ createdAt: { $gte: start, $lt: end } },
],
}).map(attendance => attendance.studentUserProfileId);
return UserProfiles.find({
$or: [
{ _id: { $in: studentUserIds } },
{
$and: [
{ [weekday]: true },
],
},
],
}),
}
// user not authorized. do not publish secrets
this.stop();
return false;
});
How about using publish-composite? It handles the "reactivity" part on its own.
https://github.com/englue/meteor-publish-composite
Im new in Vuejs. I started a project with Vue, Firebase and using Chart Js inside of it. Here is the details of problem.
If I give any value of sales_today in data() it shows properly on mounted where I use it by this.sales_today also works perfectly in template {{sales_today}}.
But into the Created I'm trying to change this.sales_today value by an output of firebase query. then the output shows perfectly into template {{sales_today}} but not working inside the mounted here
**data: [this.sales_today,30,60,10]**
Template
<template>
{{sales_today}}
</template>
Data
data(){
return{
sales_today:''
}
},
Mounted
mounted() {
data: {
datasets: [{
data: [this.sales_today,30,60,10],
}]
}
}
Created
created(){
let ref = db.collection('sales').where("sales_date", "==", moment().format('DD-MM-YYYY'))
.get()
.then(snapshot => {
var total = 0;
snapshot.forEach(doc => {
total += Number(doc.data().price)
})
this.sales_today = total
})
}
Here is the complete code
https://github.com/Shakilzaman87/pukucrm/blob/master/src/components/dashboard/Dashboard.vue
This should be on mounted(). I don't have the editor on comments and i will answer here.
let ref = db.collection('sales').where("sales_date", "==", moment().format('DD-MM-YYYY'))
.get()
.then(snapshot => {
var total = 0;
snapshot.forEach(doc => {
total += Number(doc.data().price)
})
this.sales_today = total;
var chart = this.$refs.chart;
var ctx = chart.getContext("2d");
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels:this.labels,
datasets: [{
label: 'Sales of June',
data: [this.sales_today,30,60,10],
backgroundColor: [
'#ffffff'
],
borderColor: [
'#1976d2'
],
borderWidth: 3
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
},
});
})
P.S. check the console for errors
I am trying to test my app and followed this link http://lathonez.github.io/2016/ionic-2-e2e-testing/ i merged my app with firebase. Everything worked good, but when i run npm run e2e browser opens and close immediately in my terminal pops an error.
I followed this link http://lathonez.github.io/2016/ionic-2-e2e-testing/
Actually my issue is that i could not able to see any action takes place in my e2e browser could some on help me
protractorconfig.js
exports.config = {
baseUrl: 'http://192.168.1.2:8100/',
specs: [
'../app/pages/home/home.e2e.ts',
'../app/pages/Admin/admin.e2e.ts',
//'../app/pages/Listing/lisitngPage.e2e.ts'
],
exclude: [],
framework: 'jasmine2',
allScriptsTimeout: 110000,
jasmineNodeOpts: {
showTiming: true,
showColors: true,
isVerbose: false,
includeStackTrace: false,
defaultTimeoutInterval: 400000
},
directConnect: true,
chromeOnly: true,
capabilities: {
'browserName': 'chrome',
'chromeOptions': {
'args': ['--disable-web-security']
}
},
onPrepare: function() {
var SpecReporter = require('jasmine-spec-reporter');
jasmine.getEnv().addReporter(new SpecReporter({displayStacktrace: true}));
browser.ignoreSynchronization = false;
},
useAllAngular2AppRoots: true
};
gulpfile.ts
import { join } from 'path';
const config: any = {
gulp: require('gulp'),
appDir: 'app',
testDir: 'test',
testDest: 'www/build/test',
typingsDir: 'typings',
};
const imports: any = {
gulp: require('gulp'),
runSequence: require('run-sequence'),
ionicGulpfile: require(join(process.cwd(), 'gulpfile.js')),
};
const gulp: any = imports.gulp;
const runSequence: any = imports.runSequence;
// just a hook into ionic's build
gulp.task('build-app', (done: Function) => {
runSequence(
'build',
(<any>done)
);
});
// compile E2E typescript into individual files, project directoy structure is replicated under www/build/test
gulp.task('build-e2e', ['clean-test'], () => {
let typescript: any = require('gulp-typescript');
let tsProject: any = typescript.createProject('tsconfig.json');
let src: Array<any> = [
join(config.typingsDir, '/index.d.ts'),
join(config.appDir, '**/*e2e.ts'),
];
let result: any = gulp.src(src)
.pipe(typescript(tsProject));
return result.js
.pipe(gulp.dest(config.testDest));
});
// delete everything used in our test cycle here
gulp.task('clean-test', () => {
let del: any = require('del');
// You can use multiple globbing patterns as you would with `gulp.src`
return del([config.testDest]).then((paths: Array<any>) => {
console.log('Deleted', paths && paths.join(', ') || '-');
});
});
// run jasmine unit tests using karma with PhantomJS2 in single run mode
gulp.task('karma', (done: Function) => {
let karma: any = require('karma');
let karmaOpts: {} = {
configFile: join(process.cwd(), config.testDir, 'karma.config.js'),
singleRun: true,
};
new karma.Server(karmaOpts, done).start();
});
// run jasmine unit tests using karma with Chrome, Karma will be left open in Chrome for debug
gulp.task('karma-debug', (done: Function) => {
let karma: any = require('karma');
let karmaOpts: {} = {
configFile: join(process.cwd(), config.testDir, 'karma.config.js'),
singleRun: false,
browsers: ['Chrome'],
reporters: ['mocha'],
};
new karma.Server(karmaOpts, done).start();
});
// run tslint against all typescript
gulp.task('lint', () => {
let tslint: any = require('gulp-tslint');
return gulp.src(join(config.appDir, '**/*.ts'))
.pipe(tslint())
.pipe(tslint.report('verbose'));
});
// build unit tests, run unit tests, remap and report coverage
gulp.task('unit-test', (done: Function) => {
runSequence(
['lint', 'html'],
'karma',
(<any>done)
);
});