11cb0ef41Sopenharmony_ci'use strict';
21cb0ef41Sopenharmony_ci
31cb0ef41Sopenharmony_ciconst common = require('../common');
41cb0ef41Sopenharmony_ciconst dc = require('diagnostics_channel');
51cb0ef41Sopenharmony_ciconst assert = require('assert');
61cb0ef41Sopenharmony_ciconst { Channel } = dc;
71cb0ef41Sopenharmony_ci
81cb0ef41Sopenharmony_ciconst name = 'test';
91cb0ef41Sopenharmony_ciconst input = {
101cb0ef41Sopenharmony_ci  foo: 'bar'
111cb0ef41Sopenharmony_ci};
121cb0ef41Sopenharmony_ci
131cb0ef41Sopenharmony_ci// Individual channel objects can be created to avoid future lookups
141cb0ef41Sopenharmony_ciconst channel = dc.channel(name);
151cb0ef41Sopenharmony_ciassert.ok(channel instanceof Channel);
161cb0ef41Sopenharmony_ci
171cb0ef41Sopenharmony_ci// No subscribers yet, should not publish
181cb0ef41Sopenharmony_ciassert.ok(!channel.hasSubscribers);
191cb0ef41Sopenharmony_ci
201cb0ef41Sopenharmony_ciconst subscriber = common.mustCall((message, name) => {
211cb0ef41Sopenharmony_ci  assert.strictEqual(name, channel.name);
221cb0ef41Sopenharmony_ci  assert.deepStrictEqual(message, input);
231cb0ef41Sopenharmony_ci});
241cb0ef41Sopenharmony_ci
251cb0ef41Sopenharmony_ci// Now there's a subscriber, should publish
261cb0ef41Sopenharmony_cidc.subscribe(name, subscriber);
271cb0ef41Sopenharmony_ciassert.ok(channel.hasSubscribers);
281cb0ef41Sopenharmony_ci
291cb0ef41Sopenharmony_ci// The ActiveChannel prototype swap should not fail instanceof
301cb0ef41Sopenharmony_ciassert.ok(channel instanceof Channel);
311cb0ef41Sopenharmony_ci
321cb0ef41Sopenharmony_ci// Should trigger the subscriber once
331cb0ef41Sopenharmony_cichannel.publish(input);
341cb0ef41Sopenharmony_ci
351cb0ef41Sopenharmony_ci// Should not publish after subscriber is unsubscribed
361cb0ef41Sopenharmony_ciassert.ok(dc.unsubscribe(name, subscriber));
371cb0ef41Sopenharmony_ciassert.ok(!channel.hasSubscribers);
381cb0ef41Sopenharmony_ci
391cb0ef41Sopenharmony_ci// unsubscribe() should return false when subscriber is not found
401cb0ef41Sopenharmony_ciassert.ok(!dc.unsubscribe(name, subscriber));
411cb0ef41Sopenharmony_ci
421cb0ef41Sopenharmony_ciassert.throws(() => {
431cb0ef41Sopenharmony_ci  dc.subscribe(name, null);
441cb0ef41Sopenharmony_ci}, { code: 'ERR_INVALID_ARG_TYPE' });
451cb0ef41Sopenharmony_ci
461cb0ef41Sopenharmony_ci// Reaching zero subscribers should not delete from the channels map as there
471cb0ef41Sopenharmony_ci// will be no more weakref to incRef if another subscribe happens while the
481cb0ef41Sopenharmony_ci// channel object itself exists.
491cb0ef41Sopenharmony_cichannel.subscribe(subscriber);
501cb0ef41Sopenharmony_cichannel.unsubscribe(subscriber);
511cb0ef41Sopenharmony_cichannel.subscribe(subscriber);
52