1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2025-01-05 13:59:01 -05:00

clean up debug logs

This commit is contained in:
Yoshiya Hinosawa 2024-09-26 12:45:05 +09:00
parent be8c90de6f
commit 9c1b39ba2d
No known key found for this signature in database
GPG key ID: 9017DB4559488785
10 changed files with 8 additions and 194 deletions

View file

@ -100,12 +100,10 @@ impl Resource for TcpStreamResource {
}
fn shutdown(self: Rc<Self>) -> AsyncResult<()> {
eprintln!("shutdown TcpStreamResource");
Box::pin(self.shutdown())
}
fn close(self: Rc<Self>) {
eprintln!("close TcpStreamResource");
self.cancel_read_ops();
}
}

View file

@ -328,7 +328,6 @@ where
let rid = state_
.resource_table
.add(TcpStreamResource::new(tcp_stream.into_split()));
eprintln!("adding TcpStreamResource in op_net_connect_tcp: {rid}");
Ok((rid, IpAddr::from(local_addr), IpAddr::from(remote_addr)))
}
@ -655,7 +654,6 @@ pub fn op_set_nodelay_inner(
) -> Result<(), AnyError> {
let resource: Rc<TcpStreamResource> =
state.resource_table.get::<TcpStreamResource>(rid)?;
println!("setting nodelay (rid: {rid}): {nodelay}");
resource.set_nodelay(nodelay)
}
@ -676,7 +674,6 @@ pub fn op_set_keepalive_inner(
) -> Result<(), AnyError> {
let resource: Rc<TcpStreamResource> =
state.resource_table.get::<TcpStreamResource>(rid)?;
eprintln!("setting keepalive (rid: {rid}): {keepalive}");
resource.set_keepalive(keepalive)
}

View file

@ -293,7 +293,6 @@ where
.borrow::<DefaultTlsOptions>()
.root_cert_store()?;
println!("used in op_tls_start");
let resource_rc = state
.borrow_mut()
.resource_table

View file

@ -329,7 +329,6 @@ pub fn take_network_stream_resource(
// The stream we're attempting to unwrap may be in use somewhere else. If that's the case, we cannot proceed
// with the process of unwrapping this connection, so we just return a bad resource error.
// See also: https://github.com/denoland/deno/pull/16242
println!("used in take_network_stream_resource");
if let Ok(resource_rc) = resource_table.take::<TcpStreamResource>(stream_rid)
{
// This TCP connection might be used somewhere else.

View file

@ -107,15 +107,8 @@ where
.borrow_mut()
.resource_table
.take::<TcpStreamResource>(conn_rid)?;
eprintln!(
"rc: strong_count: {strong_count} weak_count: {weak_count}",
strong_count = Rc::strong_count(&resource_rc),
weak_count = Rc::weak_count(&resource_rc)
);
let resource = Rc::try_unwrap(resource_rc).map_err(|e| {
eprintln!("error: {:?}", e);
bad_resource("TCP stream is currently in use")
})?;
let resource = Rc::try_unwrap(resource_rc)
.map_err(|e| bad_resource("TCP stream is currently in use"))?;
let (read_half, write_half) = resource.into_inner();
let tcp_stream = read_half.reunite(write_half)?;
let io = TokioIo::new(tcp_stream);
@ -128,11 +121,9 @@ where
// Spawn a task to poll the connection, driving the HTTP state
let _handle = tokio::task::spawn(async move {
eprintln!("rs: connection started");
conn_start.store(true, std::sync::atomic::Ordering::Relaxed);
let _ = notify.send(());
conn.await?;
eprintln!("rs: connection completed");
Ok::<_, AnyError>(())
});
@ -199,9 +190,6 @@ where
request.headers_mut().insert(CONTENT_LENGTH, len.into());
}
eprintln!("rs: sending request: {request:?}");
// let req_fut = sender.send_request(request);
// let res = tokio::time::timeout(Duration::from_secs(10), req_fut).await??;
let res = sender.send_request(request).map_err(Error::from).boxed();
let rid = state
.borrow_mut()
@ -248,15 +236,7 @@ pub async fn op_node_http_await_response(
let resource = Rc::try_unwrap(resource)
.map_err(|_| bad_resource("NodeHttpClientResponse"))?;
eprintln!(
"rs: awaiting response: {}",
resource
.connection_started
.load(std::sync::atomic::Ordering::Relaxed)
);
let res = resource.response.await?;
// let res = tokio::time::timeout(Duration::from_secs(10), req_fut).await??;
eprintln!("rs: received response");
let status = res.status();
let mut res_headers = Vec::new();
@ -280,7 +260,6 @@ pub async fn op_node_http_await_response(
let body = body.boxed();
let res = http::Response::from_parts(parts, body);
println!("res: {res:?}");
let response_rid = state
.borrow_mut()
@ -556,7 +535,6 @@ impl Stream for NodeHttpResourceToBodyAdapter {
Poll::Ready(res) => match res {
Ok(buf) if buf.is_empty() => Poll::Ready(None),
Ok(buf) => {
println!("rs: reading: {len}", len = buf.len());
this.1 = Some(this.0.clone().read(64 * 1024));
Poll::Ready(Some(Ok(buf.to_vec().into())))
}

View file

@ -326,7 +326,6 @@ Agent.prototype.createSocket = function createSocket(req, options, cb) {
});
const newSocket = this.createConnection(options, oncreate);
console.log("agent: creating a connection", newSocket._handle.rid);
if (newSocket) {
oncreate(null, newSocket);
}

View file

@ -498,11 +498,9 @@ Object.defineProperties(
const outputLength = this.outputData.length;
if (socket && outputLength > 0) {
const { data, encoding, callback } = this.outputData.shift();
console.log("flushBody: writing", { data });
this._writeRaw(data, encoding, callback);
if (this.outputData.length > 0) {
this.on("drain", () => {
console.log("drain emitted");
this._flushBody();
});
}
@ -512,19 +510,13 @@ Object.defineProperties(
/** Right after socket is ready, we need to writeHeader() to setup the request and
* client. This is invoked by onSocket(). */
_flushHeaders() {
console.log("flushHeaders");
if (this.socket) {
console.log("socket found: ", {
headerSent: this._headerSent,
header: this._header,
});
if (!this._headerSent) {
console.log("_writeHeader invoked");
this._writeHeader();
this._headerSent = true;
}
} else {
console.log("socket not found");
console.warn("socket not found");
}
},
@ -533,32 +525,15 @@ Object.defineProperties(
// if socket is ready, write the data after headers are written.
// if socket is not ready, buffer data in outputbuffer.
if (this.socket && !this.socket.connecting) {
console.log("_send(): im never invoked");
if (!this._headerSent && this._header !== null) {
this._writeHeader();
this._headerSent = true;
}
if (this._headerSent) {
console.log("_send(): writeRaw", data, encoding, callback);
return this._writeRaw(data, encoding, callback);
}
} else {
// if (!this._listenerSet) {
// this._listenerSet = true;
// this.on("socket", (socket) => {
// console.log("socket rid:", socket._handle.rid);
// socket.on("ready", () => {
// if (!this._headerSent && this._header !== null) {
// this._writeHeader();
// this._headerSent = true;
// }
// this._flushBuffer();
// });
// });
// }
console.log("_send(): pushing to outputData:", this.outputData.length);
this.outputData.push({ data, encoding, callback });
}
},
@ -591,7 +566,6 @@ Object.defineProperties(
}).catch((e) => {
this._requestSendError = e;
});
console.log("flushing data:", data, ret);
}
this.outputData = [];
@ -606,7 +580,6 @@ Object.defineProperties(
encoding?: string | null,
callback?: () => void,
) {
console.trace("_writeRaw invoked:", data.length);
if (typeof data === "string") {
data = Buffer.from(data, encoding);
}
@ -614,20 +587,11 @@ Object.defineProperties(
data = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
}
if (data.buffer.byteLength > 0) {
console.log(
"writing to",
this._bodyWriteRid,
"desired size",
this._bodyWriter.desiredSize,
"writer",
this._bodyWriter,
);
this._bodyWriter.ready.then(() => {
if (this._bodyWriter.desiredSize > 0) {
this._bodyWriter.write(data).then(() => {
callback?.();
if (this.outputData.length == 0) {
console.log("emitting finish for", { data });
this.emit("finish");
}
this.emit("drain");

View file

@ -50,7 +50,6 @@ import { Agent, globalAgent } from "node:_http_agent";
import { urlToHttpOptions } from "ext:deno_node/internal/url.ts";
import { kEmptyObject, once } from "ext:deno_node/internal/util.mjs";
import { constants, TCP } from "ext:deno_node/internal_binding/tcp_wrap.ts";
// import { notImplemented, warnNotImplemented } from "ext:deno_node/_utils.ts";
import { notImplemented } from "ext:deno_node/_utils.ts";
import {
@ -64,10 +63,7 @@ import {
} from "ext:deno_node/internal/errors.ts";
import { getTimerDuration } from "ext:deno_node/internal/timers.mjs";
import { serve, upgradeHttpRaw } from "ext:deno_http/00_serve.ts";
import { createHttpClient } from "ext:deno_fetch/22_http_client.js";
import { headersEntries } from "ext:deno_fetch/20_headers.js";
// import { timerId } from "ext:deno_web/03_abort_signal.js";
// import { clearTimeout as webClearTimeout } from "ext:deno_web/02_timers.js";
import { resourceForReadableStream } from "ext:deno_web/06_streams.js";
import { TcpConn } from "ext:deno_net/01_net.js";
import { STATUS_CODES } from "node:_http_server";
@ -388,7 +384,6 @@ class ClientRequest extends OutgoingMessage {
}
if (this.agent) {
console.log("use this.agent");
this.agent.addRequest(this, optsWithoutSignal);
} else {
// No agent, default to Connection:close.
@ -416,29 +411,13 @@ class ClientRequest extends OutgoingMessage {
}
} else {
debug("CLIENT use net.createConnection", optsWithoutSignal);
console.log("use net.createConnection");
this.onSocket(netCreateConnection(optsWithoutSignal));
}
}
}
_writeHeader() {
console.trace("_writeHeader invoked am i working?");
const url = this._createUrlStrFromOptions();
console.log({ url });
// const headers = [];
// for (const key in this[kOutHeaders]) {
// if (Object.hasOwn(this[kOutHeaders], key)) {
// const entry = this[kOutHeaders][key];
// console.log("processing header");
// this._processHeader(headers, entry[0], entry[1], false);
// console.log("processing header done");
// }
// }
// console.log("im here", { headers });
// const client = this._getClient() ?? createHttpClient({ http2: false });
// this._client = client;
if (
this.method === "POST" || this.method === "PATCH" || this.method === "PUT"
@ -455,18 +434,8 @@ class ClientRequest extends OutgoingMessage {
this._bodyWriteRid = resourceForReadableStream(readable);
}
// this._req = op_node_http_request(
// this.method,
// url,
// headers,
// client[internalRidSymbol],
// this._bodyWriteRid,
// );
(async () => {
try {
console.trace("js: sending request", this.socket.rid);
// console.log("this.socket", this.socket);
const [rid, connRid] = await op_node_http_request_with_conn(
this.method,
url,
@ -474,21 +443,10 @@ class ClientRequest extends OutgoingMessage {
this._bodyWriteRid,
this.socket.rid,
);
console.log("js: request sent", { rid, connRid });
// Emit request ready to let the request body to be written.
await op_node_http_wait_for_connection(connRid);
this.emit("requestReady");
const res = await op_node_http_await_response(rid);
console.log({ status: res.status });
// if (this._req.cancelHandleRid !== null) {
// core.tryClose(this._req.cancelHandleRid);
// }
// if (this._timeout) {
// this._timeout.removeEventListener("abort", this._timeoutCb);
// webClearTimeout(this._timeout[timerId]);
// }
// this._client.close();
console.log("IncomingMessageForClient constructed");
const incoming = new IncomingMessageForClient(this.socket);
incoming.req = this;
this.res = incoming;
@ -558,18 +516,10 @@ class ClientRequest extends OutgoingMessage {
this._closed = true;
this.emit("close");
} else {
console.log("emitting response");
{
console.log("_bodyRid set", res.responseRid);
incoming._bodyRid = res.responseRid;
}
incoming._bodyRid = res.responseRid;
this.emit("response", incoming);
}
} catch (err) {
// if (this._req.cancelHandleRid !== null) {
// core.tryClose(this._req.cancelHandleRid);
// }
if (this._requestSendError !== undefined) {
// if the request body stream errored, we want to propagate that error
// instead of the original error from opFetchSend
@ -613,19 +563,13 @@ class ClientRequest extends OutgoingMessage {
onSocket(socket, _err) {
nextTick(() => {
socket.on("connect", () => {
console.log("connect emitted");
// Flush the internal buffers once socket is ready.
// Note: the order is important, as the headers flush
// sets up the request.
try {
this._flushHeaders();
this.on("requestReady", () => {
console.log("onSocket: flushing body");
this._flushBody();
});
} catch (error) {
console.log("socket error: ", error);
}
this._flushHeaders();
this.on("requestReady", () => {
this._flushBody();
});
});
this.socket = socket;
this.emit("socket", socket);
@ -634,13 +578,8 @@ class ClientRequest extends OutgoingMessage {
// deno-lint-ignore no-explicit-any
end(chunk?: any, encoding?: any, cb?: any): this {
console.log("end(): invoked");
this.on("drain", () => {
console.log("drain emitted");
});
// Do nothing if request is already destroyed.
if (this.destroyed) return this;
console.log("end(): not destroyed");
if (typeof chunk === "function") {
cb = chunk;
@ -653,18 +592,10 @@ class ClientRequest extends OutgoingMessage {
this.finished = true;
if (chunk) {
console.log("end(): writing chunk", chunk);
this.write_(chunk, encoding, null, true);
} else if (!this._headerSent) {
if (this.socket && !this.socket.connecting) {
console.log("end(): socket created and sending implicit header");
this._contentLength = 0;
console.log(
"end(): _implicitHeader; socket.rid",
this.socket.rid,
"socket.connecting",
this.socket.connecting,
);
this._implicitHeader();
this._send("", "latin1");
} else {
@ -674,26 +605,9 @@ class ClientRequest extends OutgoingMessage {
if (this.socket && this._bodyWriter) {
(async () => {
try {
// const { promise, resolve } = Promise.withResolvers();
// if (this.outputData.length > 0) {
// this.on("flushBodyDone", () => {
// console.log("end(): flushBody done emitted");
// resolve(null);
// })
// } else {
// resolve(null);
// }
// // sleep for 10s
await new Promise((resolve) => setTimeout(resolve, 1000));
console.log("end(): closing bodyWriter", this._bodyWriter, {
buffer: this.outputData.length,
});
await this._bodyWriter.ready;
await this._bodyWriter?.close();
console.log("end(): bodyWriter closed");
} catch (err) {
console.log("err:", err);
console.log("end(): body writer closed", err);
// The readable stream resource is dropped right after
// read is complete closing the writable stream resource.
// If we try to close the writer again, it will result in an
@ -709,17 +623,9 @@ class ClientRequest extends OutgoingMessage {
this.on("finish", () => {
(async () => {
try {
console.log(
"end(): connect() closing bodyWriter",
this._bodyWriter,
{ buffer: this.outputData.length },
);
await this._bodyWriter.ready;
await this._bodyWriter?.close();
console.log("end(): bodyWriter closed");
} catch (err) {
console.log("err:", err);
console.log("end(): body writer closed", err);
// The readable stream resource is dropped right after
// read is complete closing the writable stream resource.
// If we try to close the writer again, it will result in an
@ -743,7 +649,6 @@ class ClientRequest extends OutgoingMessage {
}
this.aborted = true;
this.emit("abort");
//process.nextTick(emitAbortNT, this);
this.destroy();
}
@ -779,46 +684,25 @@ class ClientRequest extends OutgoingMessage {
}
_createUrlStrFromOptions(): string {
console.log("_createUrlStrFromOptions");
if (this.href) {
return this.href;
}
console.log("_createUrlStrFromOptions 2");
const protocol = this.protocol ?? this.defaultProtocol;
console.log("_createUrlStrFromOptions 3");
const auth = this.auth;
console.log("_createUrlStrFromOptions 4");
const host = this.host ?? this.hostname ?? "localhost";
console.log("_createUrlStrFromOptions 5");
const hash = this.hash ? `#${this.hash}` : "";
console.log("_createUrlStrFromOptions 6");
const defaultPort = this.agent?.defaultPort;
console.log("_createUrlStrFromOptions 7");
const port = this.port ?? defaultPort ?? 80;
console.log("_createUrlStrFromOptions 8");
let path = this.path ?? "/";
if (!path.startsWith("/")) {
path = "/" + path;
}
console.log("_createUrlStrFromOptions 9");
// try {
console.log({
url: `${protocol}//${auth ? `${auth}@` : ""}${host}${
port === 80 ? "" : `:${port}`
}${path}`,
});
const url = new URL(
`${protocol}//${auth ? `${auth}@` : ""}${host}${
port === 80 ? "" : `:${port}`
}${path}`,
);
console.log(url);
// } catch (error) {
// console.log({ error })
// }
console.log("_createUrlStrFromOptions 10");
url.hash = hash;
console.log("_createUrlStrFromOptions end");
return url.href;
}
@ -1040,7 +924,6 @@ export class IncomingMessageForClient extends NodeReadable {
const buf = new Uint8Array(16 * 1024);
core.read(this._bodyRid, buf).then((bytesRead) => {
console.log(`bytes read from ${this._bodyRid}:`, bytesRead);
if (bytesRead === 0) {
this.push(null);
} else {

View file

@ -376,10 +376,8 @@ export class TCP extends ConnectionWrap {
transport: "tcp",
};
console.log("deno.connect start");
Deno.connect(connectOptions).then(
(conn: Deno.Conn) => {
console.log("deno.connect success");
// Incorrect / backwards, but correcting the local address and port with
// what was actually used given we can't actually specify these in Deno.
const localAddr = conn.localAddr as Deno.NetAddr;

View file

@ -22,7 +22,6 @@ fn op_http_start(
state: &mut OpState,
#[smi] tcp_stream_rid: ResourceId,
) -> Result<ResourceId, AnyError> {
println!("used in op_http_start");
if let Ok(resource_rc) = state
.resource_table
.take::<TcpStreamResource>(tcp_stream_rid)